Repozytorium Web Developera

JavaScript - Vanilla and DOM operations

Element properties

Most popular properties.

  • .attributes
  • .childElementCount
  • .childNodes - array
  • .children
  • .classList
  • .className
  • .firstChild
  • .firstElementChild
  • .id
  • .innerHTML
  • .innerText
  • .lastChild
  • .lastElementChild
  • .nodeName
  • .nodeType
  • .outerHTML
  • .outerText
  • .ownerDocument
  • .parentElement
  • .parentNode
  • .previousSibling
  • .style
  • .tagName
  • .textContent

Getting HTML elements or collections

Get one element by selector

Returns Element.


document.querySelector(selector)
// example
document.querySelector('.profile')

Get all elements by selector

Returns NodeList object of Nodes (also Elements).


document.querySelectorAll(selector)
// example
document.querySelectorAll('.profile')

Get all elements by tag

For example, div or a.

Returns an HTMLCollection of Elements.


document.getElementsByTagName(tag)
// example
document.getElementsByTagName('div')

Get element by id

For example, #shop.


document.getElementById('shop')

Elements creation

Create element node

tag is for example li.


var node = document.createElement(tag)

Create text node

text is string.


var textnode = document.createTextNode(text)

Create node with text node

text is string.


var node = document.createElement(tag)
var textnode = document.createTextNode(text)
node.appendChild(textnode)

DOM manipulation

  • .replaceChild(newChild, oldChild)
  • .appendChild(child)
  • .removeChild(child)
  • .insertBefore(oldPosition, newPosition)
  • .cloneNode(deep ? true : false)
  • .hasChildNodes()

Add element to DOM element


var node = ...
document.getElementById('id').appendChild(node)

Take lastChild of node and append it to another node


var node = document.getElementById('list').lastChild
document.getElementById('special-list').appendChild(node)

Put last element of list before its first element


var ul = ... // get ul element
ul.insertBefore(ul.lastChild, ul.firstChild)

<ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
</ul>

const ul = document.getElementsByTagName('ul')

const list = ul[0]

list.insertBefore(list.lastElementChild, list.firstElementChild)