You can use css style selectors or relational selectors.
<div id="container">
<div class="display"></div>
</div>
To select the div display:
css style:
Relational:
firsElementChildlastElementChildconst container = document.querySelector('#container');
const x = container.firsElementChild
const y = document.querySelector('.controls');
Each nodes of the DOM are object with properties and methods that allow web page manipulation.
| methods | description | example |
|---|---|---|
| document.querySelector(selector) | return reference to the first match | |
| document.querySelectorAll(selectors) | return nodelist with references to all matches |
Note: the return value of
.querySelectorAllisnotan array, it is anodelist. Some array methods don’t apply to it, unless converted to an array withArray.from()for example.
document.createElement(tagName, [option])
const div = document.createElement('div');
Note: it only creates the element, it does not insert it in the DOM.
You can use a reference to an element to alter its properties.
// create a reference
const div = document.createElement('div');
div.style.color = 'blue';
div.style.cssText = 'color: blue; background: white;';
div.setAttribute('style', 'color: blue; background: white;');
Note: for kebab-cased css, you need to modify the notation: > div.style.
background-color// does not work use one of these: > div.style.backgroundColor > div.style[‘background-color’] > div.style.cssText = “background-color: white;”
Add a class or id…
setAttribute(attributesType, attributesName);
If the attributesName provided does not exitst, it create it.
div.setAttribute('id', 'theDiv');
div.getAttribute('id'); // will return 'theDiv'
div.removeAttribute('id');
With classes:
div.classList.add('new');
div.classList.remove('new');
div.classList.toggle('active');
!!There is no dot when adding a class, it is("className")not (“.className”)
Note: it is better to use
.togglerather than add or remove.
div.textContent = "Hello, World!";
div.innerHTML = "<span>Hello, World!</span>";
Note:
textContentshould be prefer because less prone to javascript injection.