DOM operations (get, add, delete elements)

When programming in Javascript, there are times when you want to manipulate HTML elements directly. In such cases, knowledge of DOM manipulation is necessary. This section explains basic DOM manipulation methods (getting, adding, and deleting elements).


Retrieving Elements

methodDescription.return value
document.getElementById(id)Get element by idElement
document.getElementsByClassName(name)Get element by classHTMLCollection
document.getElementsByName(name)Get element by name attributeNodeList
document.getElementsByTagName(name)Get element by tag nameHTMLCollection
document.querySelector(selectors)Get element (first one) with selectorElement
document.querySelectorAll(selectors)Get element(s) with selectorNodeList

HTMLCollection and NodeList are almost identical. Both do not have forEach, so if you want to loop through the elements, do the following

const elements = document.getElementsByTagName('div'), element => {

Node walking

This is a method of acquiring another node from one node as a base point.

element.parentNodecontaining element
element.firstElementChildfirst child element
element.lastElementChildLast child element
element.childrenchild element list
element.previousElementSibling1 previous element
element.nextElementSiblingOne element later

There is also firstChild. This returns the first child node. Nodes include the following.

  • node
    • Element (node)
    • attribute node
    • character string node

In other words, in addition to elements (nodes), string nodes, etc. are also included.

Rewriting HTML Elements

innerHTML to access HTML elements.

element.innerHTML = '<div>xxxxx</div>'

Attribute manipulation

element.getAttribute(name)Get specified attributes
element.setAttribute(name, value)Set specified attributes
element.removeAttribute(name)Delete specified attribute

Create, add, delete elements

document.createElement(name)Create element with specified tag
node.insertBefore(newElement, referenceElement)Add newElement before referenceElement
node.appendChild(newElement)Added as last child element
node.removeChild(child)Delete child node

Examples of Use

<ul id="list">
const element = document.getElementById('list')

// Added as first child element
const liFirst = document.createElement('li')
liFirst.textContent = 'aaaaa'
element.insertBefore(liFirst, element.firstChild)

// Added as last child element
const liLast = document.createElement('li')
liLast.textContent = 'ddddd'
<ul id="list">

Element width, height, line width

Let's share this post !