Native JS DOM manipulation

<div class="layout" id="layout">
    <div id="item1" class="item1">1</div>
    <div id="item2" class="item2">2</div>
    <div class="item1">3</div>
    <input type="text" name="input">
</div>
Copy the code

Create the element

document.createElement(‘div’)
Document.createtextnode (‘ createTextNode ‘)
document.createDocumentFragment()
Get elements:
document.getElementById(‘layout’); // Obtain by id
document.etElementsByClass(‘layout’); // Get by class name
document.getElementsByTagName(); // By the tag name
document.getElementsByName(‘input’); (Only elements with a name attribute (form elements) can be retrieved by the name attribute)
document.querySelector(‘.item1’); // According to the selector
document.querySelectorAll(‘.item1’);
document.documentElement; // Get the HTML tag
document.body; // Get the body tag

Operation elements:

    const parentNode = document.getElementById('layout')
    const createNode = document.createElement('div')
    createNode.innerHTML = 'Create new node'
    const oldNode =  document.querySelector('.item1')
Copy the code
parentNode.appendChild(createNode)
ParentNode. InsertBefore (createNode oldNode)
parentNode.removeChild(oldNode)
ParentNode. ReplaceChild (createNode oldNode)
Document.getelementbyid (‘item1’).clonenode (Boolean) // Clone all descendants, set Boolean to true, otherwise set Boolean to false.
Document.getelementbyid (‘ Item1 ‘).innerhtml = ‘Create new node’
Document.getelementbyid (‘ Item1 ‘). InnerText = ‘Create new node’

Access to the node

Oldnode. previousSibling // previousSibling node
Oldnode. nextSibling // nextSibling node
Oldnode. parentNode // parentNode
parentNode.childNode
parentNode.children
parentNode.firstChild
parentNode.lastChild

attribute

oldNode.getAttribute(‘class’)
oldNode.setAttribute(‘class’,’new-class’)
oldNode.removeAttribute(‘class’)
oldNode.hasAttribute(‘class’)

class

oldNode.classList.add(“class1”, “class2”, “class3”); —- Add the class name. If there is a class name, do not add it
Oldnode.setattribute (“class”,getAttribute(“class”).concat(‘ class4’)) —- Adds the class name
oldNode.classList.remove(“class1”); —- removes the class name from the list
Oldnode.setattribute (“class”,getAttribute(“class”).replace(oldClase, “”)) —- removes the class name from the list
Oldnode.classlist.toggle (‘class1’) —- Toggle class name: Delete it if it exists in the list, add it otherwise
OldNode. ClassList. The contains (‘ class1) – judge whether there is the name of the class, returns a Boolean value