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).

TOC

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')
Array.prototype.forEach.call(elements, element => {
  console.log(element)
})

Node walking

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

propertyDescription.
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

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

Create, add, delete elements

methodDescription.
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">
  <li>bbbbb</li>
  <li>ccccc</li>
</ul>
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'
element.appendChild(liLast)
<ul id="list">
  <li>aaaaa</li>
  <li>bbbbb</li>
  <li>ccccc</li>
  <li>ddddd</li>
</ul>

Element width, height, line width

Let's share this post !
TOC