Walking the DOM
輕而易舉用原生 code manipulate element nodes
Definition | Example | |
---|---|---|
Create/Remove element | ||
document.createElement(tag) | To create DOM nodes |
|
elem.remove() | remove a node | |
elem.cloneNode(true) |
|
|
Select element | ||
returns the first element for the given CSS selector. |
| |
document.getElementById |
| |
returns all elements inside |
| |
document.getElementsBy* | looks for elements with the given tag and returns the collection of them |
|
Insertion methods | ||
node.append(...nodes or strings) | append nodes or strings at the end of | |
node.prepend(...nodes or strings) | insert nodes or strings at the beginning of | |
node.before(...nodes or strings) | insert nodes or strings before | |
node.after(...nodes or strings) | insert nodes or strings after | |
node.replaceWith(...nodes or strings) | replaces | |
Method | ||
elem.matches | Previous methods were searching the DOM. |
|
looks for the nearest ancestor that matches the CSS-selector. |
| |
Change Some content | ||
elem.innerHTML | allows to get the HTML inside the element as a string. |
|
elem.textContent | return pure text inside the element |
|
Styles and classes | ||
elem.className | replaces the whole string of classes | |
elem.classList | add/remove a single class |
|
elem.style.{style} | an object that corresponds to what’s written in the | elem.style.margin = '20px' |
' |
Select element
Insert element
Change Some content
Styles and classes
Attribute
HTML attributes have the following features:
Their name is case-insensitive (
id
is same asID
).Their values are always strings, but properties are not always strings. For instance, the
input.checked
property (for checkboxes) is a boolean:
elem.hasAttribute(name)
– checks for existence.elem.getAttribute(name)
– gets the value.elem.setAttribute(name, value)
– sets the value.elem.removeAttribute(name)
– removes the attributeele.attributes
- a collection of objects that belong to a built-in Attr class, withname
andvalue
properties.
dataset
All attributes starting with “data-” are reserved for programmers’ use. They are available in the dataset
property.
Last updated