Day 5 - JavaScript - DOM manipulate
What is the DOM?
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. A Web page is a document. This document can be either displayed in the browser window or as the HTML source.
JavaScript basic syntax
GetElementById
var byId = document.getElementById('exampleId');
console.log(byId.id);
//output = exampleId
GetElementsByTagName
var byId = document.getElementsByTagName('p');
GetElementsByClassName
var byId = document.getElementsByClassName('testClass')[0];
console.log(byId.className);
// output = "testClass"
Changing HTML elements
innerHtml
var byId = document.getElementById('exampleId');
console.log(byId.id);
byId.innerHTML = "New div content";
Adding and deleting elements
//adding
var btn = document.createElement('button');
document.body.appendChild(btn);
//deleteing
var div1 = document.getElementById('id1');
div1.remove();
Add class
var div1 = document.getElementById('id1');
div1.className += ' newClass';
//output = <div class='oldCLass newClass'></div>
Set attribute
var div1 = document.getElementById('id1');
div1.setAttribute('class', 'newClass');
//output = <div class='newClass'></div>