JavaScript core DOM operations

1. DOM introduction

1.1 what is DOM

Document Object Model (DOM) is a standard programming interface recommended by W3C organization to deal with extensible markup language (HTML or XML). W3C has defined a series of DOM interfaces, which can change the content, structure and style of web pages.

1.2 DOM tree

  • Document: a page is a document, which is represented by document in DOM
  • Element: all tags in the page are elements, which are represented by element in DOM
  • Node: all contents in a web page are nodes (labels, attributes, text, comments, etc.), which are represented by node in DOM
  • DOM treats all of the above as objects

2. Get element

2.1 how to get page elements

DOM is mainly used to manipulate elements in actual development. The following methods can be used to obtain elements in the page:

  • Get by ID
  • Get by tag name
  • Get through the new method in HTML5
  • Special element acquisition

2.2 get by ID

Use the getElementById() method to get the element object with ID.


Use console Dir () can print the element object we get and better view the attributes and methods in the object.

    <div id="time">2019-9-9</div>
        // 1. Because the document page is loaded from top to bottom, there must be a label first, so the script is written below the label
        // 2. get the element by through the hump naming method 
        // 3. The parameter id is a case sensitive string
        // 4. An element object is returned
        var timer = document.getElementById('time');
        // 5. console.dir prints the returned element object to better view the properties and methods inside

2.3 get by tag name

Use the getElementsByTagName() method to return a collection of objects with the specified tag name.

 document.getElementsByTagName('Tag name');

be careful:

  1. Because the result is a collection of objects, you need to traverse if you want to operate the elements inside.
  2. The resulting element object is dynamic
  3. If the element cannot be obtained, an empty pseudo array is returned (because the object cannot be obtained)

You can also get all child elements with specified tag names inside an element (parent element).

element.getElementsByTagName('Tag name');
<ol id="ol">
    <li>Rare words</li>
    <li>Rare words</li>

    // 1. The returned is the collection of obtained element objects stored in the form of pseudo array
    var lis = document.getElementsByTagName('li');
    console.log(lis[0]); //Output first
    // 2. Print the element objects in turn. You can traverse them
    for (var i = 0; i < lis.length; i++) {
    // 3. If there is only one li in the page, it is still in the form of pseudo array 
    // 4. If there is no such element in the page, the form of empty pseudo array is returned
    // 5. element.getElementsByTagName('tag name '); The parent element must be the specified single element
    var ol = document.getElementById('ol');

Note: the parent element must be a single object (which element object must be specified). The parent element itself is not included in the acquisition.

2.4 get through the new method in HTML5

1. document.getElementsByClassName('class name ')// Returns a collection of element objects based on the class name
2. document.querySelector('selector '); / / returns the first element object according to the specified selector
3. document.querySelectorAll('selector '); / / return according to the specified selector

Note: the selectors in queryselector and querySelectorAll need to be signed, such as document querySelector('#nav');

<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div id="nav">
        <li>home page</li>
    // 1. getElementsByClassName obtains some element collections according to the class name
    var boxs = document.getElementsByClassName('box');
    // 2. querySelector returns the first element object of the specified selector. Remember that the selector in it needs to be signed box  #nav
    var firstBox = document.querySelector('.box');
    var nav = document.querySelector('#nav');
    var li = document.querySelector('li');
    // 3. querySelectorAll() returns the collection of all element objects of the specified selector
    var allBox = document.querySelectorAll('.box');
    var lis = document.querySelectorAll('li');

2.5 get special elements (body, html)

2.5. 1 get the body element

doucumnet.body / / returns the body element object

2.5. 2 get html elements

document.documentElement / / returns an html element object

3. Event basis

3.1 event overview

JavaScript can create dynamic pages, and events are behaviors that can be detected by JavaScript. Simple understanding: trigger response mechanism. Each element in the web page can generate some events that can trigger JavaScript. For example, an event can be generated when the user clicks a button, and then perform some operations.

3.2 three elements of event

1. Event source (who) 2. Event type (what event) 3. Event handler (what to do)

<button id="btn">Tang Bohu</button>
// Click a button to pop up a dialog box
// Event is a three part event source event type event handler called event three elements
//(1) Event source the object whose button the event is triggered
var btn = document.getElementById('btn');
//(2) How do event types trigger events, such as onclick, mouse over or keyboard down
//(3) The event handler is completed by a function assignment
btn.onclick = function() {
    alert('Point Qiuxiang');

3.3 steps to execute the event

1. Get event source} 2 Register event (binding event) 3. Add event handler (in the form of function assignment)

    // Perform event steps
    // Click the div console output, and I'm selected
    // 1. Get event source
    var div = document.querySelector('div');
    // 2. Binding event registration event
    // div.onclick 
    // 3. Add event handler 
    div.onclick = function() {
        console.log('I was chosen');


3.4 common mouse events

4. Operation elements

The DOM operation of JavaScript can change the content, structure and style of web pages. You can use DOM operation elements to change the content, attributes, etc. in elements. Note that the following are attributes:

4.1 change element content


The content from the start position to the end position, but it removes html tags, as well as spaces and line breaks


All contents from the start position to the end position, including html tags, while retaining spaces and line breaks

    I am writing
    // The difference between innerText and innerHTML 
    // 1. innerText does not recognize html tags. Non standard removal of spaces and line breaks
    var div = document.querySelector('div');
    div.innerText = '<strong>Today is:</strong> 2021';
    // 2. innerHTML recognizes html tags. W3C standard retains spaces and line breaks
    div.innerHTML = '<strong>Today is:</strong> 2022';
    // These two attributes are readable and writable, and you can get the contents of the element
    var p = document.querySelector('p');
    console.log(p.innerText); //I am text 123
    console.log(p.innerHTML); //(first line) I'm text (second line) < span > 123</span>

4.2 attribute operation of common elements

  1. innerText, innerHTML change element content
  2. src,href
  3. id,alt,title
<button id="ldh">Lau Andy</button>
<button id="zxy">Xue You Zhang</button> <br>
<img src="images/ldh.jpg" alt="" title="Lau Andy">

    // Modify element attribute src
    // 1. Get element
    var ldh = document.getElementById('ldh');
    var zxy = document.getElementById('zxy');
    var img = document.querySelector('img');
    // 2. Register event handlers
    zxy.onclick = function() {
        img.src = 'images/zxy.jpg';
        img.title = 'Xue You Zhang';
    ldh.onclick = function() {
        img.src = 'images/ldh.jpg';
        img.title = 'Lau Andy';

Case: time sharing greetings and displaying different pictures

According to different times, the page displays different pictures and different greetings at the same time.

  • If you open the page at morning time, good morning is displayed, and the picture of morning is displayed.
  • If you open the page in the afternoon, good afternoon is displayed and the picture of afternoon is displayed.
  • If you open the page at night, it will show good evening and show the picture of evening.
<img src="images/s.gif" alt="">
<div>Good morning</div>
    // It is determined according to different time of the system, so the date built-in object is required
    // Use multi branch statements to set different pictures
    // If you need a picture and modify the picture according to time, you need to use the src attribute of the operation element
    // You need a div element to display different greetings. You can modify the content of the element
    // 1. Get element
    var img = document.querySelector('img');
    var div = document.querySelector('div');
    // 2. Get the current hours
    var date = new Date();
    var h = date.getHours();
    // 3. Judge the number of hours and change the picture and text information
    if (h < 12) {
        img.src = 'images/s.gif';
        div.innerHTML = 'Good morning';
    } else if (h < 18) {
        img.src = 'images/x.gif';
        div.innerHTML = 'Good afternoon';
    } else {
        img.src = 'images/w.gif';
        div.innerHTML = 'Good evening';


4.3 attribute operation of form elements

Using DOM, you can manipulate the attributes of the following form elements:


<input type="text" value="Input content">
    // 1. Get element
    var btn = document.querySelector('button');
    var input = document.querySelector('input');
    // 2. Register event handlers
    btn.onclick = function() {
        // input.innerHTML = 'clicked'// There is no change, because this is an ordinary box (such as the content in the div tag)
        // The value text content in the form is modified through value
        input.value = 'It was clicked';
        // If you want a form to be disabled, you can no longer click the disabled button to disable it
        btn.disabled = true;
        this.disabled = true;//You can also use this
        // this refers to the caller btn of the event function

Case: show or hide passwords

  • Core idea: click the eye button, change the password box type to the text box, and you can see the password inside. One button has two states. Click once to switch to the text box, and continue to click once to switch to the password box
  • Algorithm: use a flag variable to judge the value of flag. If it is 1, switch to text box, flag is set to 0, if it is 0, switch to password box, flag is set to 1
<div class="box">
    <label for="">
        <img src="images/close.png" alt="" id="eye">
    <input type="password" name="" id="pwd">
    // 1. Get element
    var eye = document.getElementById('eye');
    var pwd = document.getElementById('pwd');
    // 2. Register event handlers
    var flag = 0;
    eye.onclick = function() {
        // After clicking once, the flag must change
        if (flag == 0) {
            pwd.type = 'text'; //Change password box type to text box
            eye.src = 'images/open.png';
            flag = 1; // Assignment operation
        } else {
            pwd.type = 'password';
            eye.src = 'images/close.png';
            flag = 0;

4.4 style attribute operation

Modify the size, color, position and other styles of elements through JS.

1. inline style operation
2. element.className class name style operation

        div {
            width: 100px;
            height: 100px;
            background-color: pink;
        .change {
            background-color: purple;
            color: #fff;
            font-size: 25px;
            margin-top: 100px;

    <div class="first">text</div>
        var test = document.querySelector('div');
        test.onclick = function() {
      // 1. Use element Style gets and modifies the element style. It is used when there are few styles or simple functions
   = 'purple';
   = '#fff';
   = '25px';
   = '100px';

      // 2. You can change the style of an element by modifying its className, which is suitable for situations with many styles or complex functions
            // Change the class name of the current element to change
            this.className = 'change';
      // 3. If you want to keep the original class name, you can do this multiple class name selector
            this.className = 'first change';

be careful:

  1. The style in JS adopts hump naming method, such as fontSize and backgroundColor
  2. JS modify style operation produces inline style, with high CSS weight
  3. If the style is modified more, you can change the element style by operating the class name.
  4. Class is a reserved word, so className is used to manipulate the element class name attribute
  5. className will directly change the class name of the element and overwrite the original class name.

4.5 summary of operation elements

Operation elements are the core content of DOM

Case: Circular sprite background

//Core idea: use the for loop to modify the background position of the sprite image
<div class="box">
    // Get all the small li of the element 
    var lis = document.querySelectorAll('li');
    for (var i = 0; i < lis.length; i++) {
        // Multiplying the index number by 44 is the background y coordinate of each li, and index is the Y coordinate
        var index = i * 44;
        lis[i].style.backgroundPosition = '0 -' + index + 'px';

Case: show or hide text box content

When the mouse clicks the text box, the default text inside is hidden. When the mouse leaves the text box, the text inside is displayed.

  1. First of all, the form needs two new events to get the focus onfocus and lose the focus onblur
  2. If you get the focus, judge whether the content in the form is the default text. If it is the default text, clear the form content
  3. If the focus is lost, judge whether the form content is empty. If it is empty, the form content will be changed to the default text
<input type="text" value="mobile phone">
    // 1. Get element
    var text = document.querySelector('input');
    // 2. Register the event to get the focus event onfocus 
    text.onfocus = function() {
            // console.log('got focus');
            if (this.value === 'mobile phone') {
                this.value = '';
            // To get focus, you need to turn the text color in the text box black
   = '#333';
        // 3. Registration event lost focus event onblur
    text.onblur = function() {
        // console.log('lost focus');
        if (this.value === '') {
            this.value = 'mobile phone';
        // To lose focus, you need to lighten the text color in the text box = '#999';

Case: password box verification information

<div class="register">
    <input type="password" class="ipt">
    <p class="message">Please enter 6~16 Bit cipher</p>
    // The first event to judge is that the form loses focus onblur
    // If the input is correct, the correct information will be prompted. The color is green and the small icon changes
    // If the input is not 6 to 16 bits, the error message color will be red and the small icon will change
    // Because there are many styles changing inside, the style is modified by className
    // 1. Get element
    var ipt = document.querySelector('.ipt');
    var message = document.querySelector('.message');
    //2. Registration events lose focus
    ipt.onblur = function() {
        // According to the length of the value in the form, IPT value. length
        if (this.value.length < 6 || this.value.length > 16) {
            // console.log('error ');
            message.className = 'message wrong'; //Multi class name selector
            message.innerHTML = 'The number of digits you entered does not require 6~16 position';
        } else {
            message.className = 'message right';
            message.innerHTML = 'Your input is correct';

4.6} exclusivity

If you have the same group of elements and want an element to implement a certain style, you need to use the exclusive idea algorithm of the loop:

  1. Clear styles for all elements
  2. Style the current element
  3. Note that the order cannot be reversed
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
<button>Button 4</button>
<button>Button 5</button>
    // 1. Get all button elements
    var btns = document.getElementsByTagName('button');
    // btns gets every element in the pseudo array btns[i]
    for (var i = 0; i < btns.length; i++) {
        btns[i].onclick = function() {
            // (1) First remove all the button background colors and kill everyone
            for (var i = 0; i < btns.length; i++) {
                btns[i].style.backgroundColor = '';
            // (2) Then let the current element background color be pink, leaving itself
   = 'pink';
    //2. First exclude others, and then set your own style. This idea of excluding others becomes exclusive

4.7} user defined attribute operation

1. Get attribute value

  • element. Property} gets the property value.
  • element.getAttribute('attribute ');


  • element. Attribute} get the built-in attribute value (the attribute of the element itself)
  • element.getAttribute('attribute '); Mainly get custom attributes (standard) programmer custom attributes

2. Set attribute value

  • element. Attribute = 'value' sets the built-in attribute value.
  • element.setAttribute('attribute ',' value ');


  • element. Property} sets the value of the built-in property
  • element.setAttribute('attribute '); Mainly set custom properties (standard)

3. Remove attributes

  • element.removeAttribute('attribute ');
<div id="demo" index="1" class="nav"></div>
    var div = document.querySelector('div');
    // 1. Get the attribute value of the element
    // (1) element. attribute
    //(2) element.getAttribute('attribute ') get the meaning of getting the attribute attribute. The attribute you add is called user-defined attribute index
    // 2. Set element attribute value
    // (1) element. Attribute = 'value' = 'test';
    div.className = 'navs';
    // (2) element.setAttribute('attribute ',' value '); Mainly for custom attributes
    div.setAttribute('index', 2);
    div.setAttribute('class', 'footer'); // Class is special. It says class, not className
    // 3 remove the attribute removeattribute (attribute)    

4.8} H5 custom attributes

Custom attribute purpose: to save and use data. Some data can be saved to the page instead of the database. Custom attributes are obtained through getAttribute('attribute '). However, some custom attributes are easy to cause ambiguity. It is not easy to judge whether they are built-in attributes or custom attributes of elements. H5 added custom attribute:

4.8. 1. Set H5 custom attribute

  • H5 specifies that the beginning of the custom attribute data - is used as the attribute name and assigned a value.
  • For example, < div data index = "1" > < / div >
  • Or use JS settings
  • element.setAttribute('data-index', 2)

4.8. 2. Get H5 custom attribute

  • Get compatibility element getAttribute(‘data-index’); Good compatibility, common
  • H5 new element dataset. Index or element Data set ['index'] ie11 began to support
<div getTime="20" data-index="2" data-list-name="andy"></div>
    var div = document.querySelector('div');
    div.setAttribute('data-time', 20);
    // h5 is a new method to get custom attributes. It can only get the attributes beginning with data -
    // dataset is a collection containing all custom attributes starting with data
    // If there are multiple - linked words in the custom attribute, the hump naming method shall be adopted when obtaining

5. Node operation

5.1 why learn node operations

There are usually two ways to obtain elements (both of which can obtain element nodes, but the node operation is simpler):

1. Use the method provided by DOM to obtain elements

  • document.getElementById()
  • document.getElementsByTagName()
  • document.querySelector, etc
  • Not logical and cumbersome

2. Obtain elements by using node hierarchy

  • Using parent-child sibling node relationship to obtain elements
  • Strong logic, but poor compatibility

5.2 node overview

All contents in a web page are nodes (tags, attributes, text, comments, etc.), which are represented by nodes in the dom. All nodes in the HTML DOM tree can be accessed through JavaScript, and all HTML elements (nodes) can be modified, created or deleted.

Generally, nodes have at least three basic attributes: nodeType, nodeName and nodeValue. In actual development, node operations mainly operate on element nodes.

  • Element node {nodeType} is 1
  • Attribute node {nodeType} is 2
  • Text node {nodeType} is 3 (text node includes text, space, line feed, etc.)

5.3 node level

Using DOM tree, nodes can be divided into different hierarchical relationships, commonly parent-child brother hierarchical relationships.

5.3. 1. Parent node


var erweima = document.querySelector('.erweima');
  • The parentNode property returns the parent node of a node. Note that it is the nearest parent node
  • Returns null if the specified node has no parent node

5.3. 2. Child nodes

 1. parentNode.childNodes (standard)

parentNode.childNodes returns a collection of child nodes containing the specified node, which is a collection of immediate updates.

Note: the return value contains all child nodes, including element nodes, text nodes, etc. If you only want to obtain the element nodes inside, you need to deal with them specially, so it is generally not recommended to use childNodes.

var ul = document. querySelector('ul');
for(var i = 0; i < ul.childNodes.length;i++) {
if (ul.childNodes[i].nodeType == 1) {    // ul.childNodes[i] is an element node

 2. parentNode.children (non-standard)

//children get all child element nodes

parentNode.children is a read-only attribute that returns all child element nodes. It only returns child element nodes, and other nodes do not return. Although children is a non-standard, it is supported by various browsers, so it is often used.

  3. parentNode.firstChild  

firstChild returns the first child node. If it cannot be found, it returns null. Similarly, it contains all nodes.

  4. parentNode.lastChild    

lastChild returns the last child node. If it cannot be found, it returns null. Similarly, it contains all nodes.

 5. parentNode.firstElementChild  

firstElementChild returns the first child element node. If it cannot be found, it returns null.

 6. parentNode.lastElementChild    

lastElementChild returns the last child element node. If it cannot be found, it returns null.  

Note: the two methods 5 and 6 have compatibility problems, which can only be supported above IE9.

var ol = document.querySelector('ol');
// 1. The first child node of firstchild is either a text node or an element node
// 2. firstElementChild returns the first child element node ie9 to support
// 3. The actual development method has no compatibility problem and returns the first child element
console.log(ol.children[ol.children.length - 1]);

In the actual development, firstChild and lastChild contain other nodes, which is inconvenient to operate, and firstElementChild and lastElementChild have compatibility problems, so how to obtain the first child element node or the last child element node?


  1. If you want the first child element node, you can use parentnode chilren[0]
  2. If you want the last child element node, you can use parentnode chilren[parentNode.chilren.length - 1]  

5.3. 3. Brother node

 1. node.nextSibling  

nextSibling returns the next sibling element node of the current element. If it cannot be found, it returns null. Similarly, it contains all nodes.

 2. node.previousSibling    

previousSibling returns the previous sibling element node of the current element. If it cannot be found, it returns null. Similarly, it contains all nodes.

 3. node.nextElementSibling  

Nextlementsibling returns the next sibling element node of the current element. If it is not found, it returns null.

 4. node.previousElementSibling    

previousElementSibling returns the previous sibling node of the current element. If it cannot be found, it returns null.

Note: the two methods 3 and 4 have compatibility problems, which are supported only when they are above IE9.

Q: how to solve the compatibility problem? A: encapsulate a compatible function yourself

   function getNextElementSibling(element) {
       var el = element;
       while (el = el.nextSibling) {
        if (el.nodeType === 1) {
            return el;
      return null;

5.4 creating nodes


document. The createElement () method creates the HTML element specified by tagName. Because these elements did not exist before and were generated dynamically according to requirements, they are also called dynamically creating element nodes.

5.5 adding nodes

 1. node.appendChild(child) //node parent child

node. The appendchild() method adds a node to the end of the child node list of the specified parent node (similar to the push in the array). It is similar to the after pseudo element in CSS.

 2. node.insertBefore(child, specify element)

node. The insertBefore () method adds a node before the specified child node of the parent node. Similar to the before pseudo element in CSS.

    // 1. Create node element node
    var li = document.createElement('li');
    // 2. Add node AppendChild (child) node the parent child is the child, followed by additional elements, similar to the push in the array
    var ul = document.querySelector('ul');
    // 3. Add node InsertBefore (child, specifies the element);
    var lili = document.createElement('li');
    ul.insertBefore(lili, ul.children[0]);
    // 4. Want to add a new element to the page: 1 Create element 2 Add element

5.6 delete node


 node. The removechild () method deletes a child node from the DOM and returns the deleted node.

Simple message board case:

<textarea name="" id=""></textarea>
    // 1. Get element
    var btn = document.querySelector('button');
    var text = document.querySelector('textarea');
    var ul = document.querySelector('ul');
    // 2. Registration event
    btn.onclick = function () {
        if (text.value == '') {
            alert('You have not entered anything');
            return false;
        } else {
            // console.log(text.value);
            // (1) Create element
            var li = document.createElement('li');
            // The value can only be assigned after li (javascript:void(0) needs to be added to prevent link jump); Or javascript:;)
            li.innerHTML = text.value + "<a href='javascript:;'>delete</a>";
            // (2) Add element
            // ul.appendChild(li);
            ul.insertBefore(li, ul.children[0]);
            // (3) Delete element deletes the currently linked li and its parent
            var as = document.querySelectorAll('a');
            for (var i = 0; i < as.length; i++) {
                as[i].onclick = function () {
                    // node.removeChild(child);  Delete li this, where li is currently a parentNode;

5.7 replication node (clone node)


node. The cloneNode () method returns a copy of the node that called the method. Also known as clone node / copy node

be careful:

  1. If the parenthesis parameter is empty or false, it is a shallow copy, that is, only the replication node itself is cloned, and the child nodes inside are not cloned.
  2. If the parenthesis parameter is true, it is a deep copy, and the node itself and all its child nodes will be copied.

5.8 differences among three dynamic creation elements

  • document.write()  
  • element.innerHTML  
  • document.createElement()


  1. document.write is the content stream that directly writes the content to the page, but when the document stream is completed, it will cause all pages to be redrawn
  2. innerHTML is to write the content to a DOM node, which will not cause all pages to be redrawn. It is more efficient to create multiple elements (do not splice strings (it is time-consuming) and splice them in the form of arrays), and the structure is slightly complex
  3. createElement() is a little less efficient in creating multiple elements, but its structure is clearer

Summary: innerHTML is more efficient than createElement in different browsers

6. DOM key core

The Document Object Model (DOM) is a standard programming interface recommended by W3C to handle extensible markup language (HTML or XML). W3C has defined a series of DOM interfaces, which can change the content, structure and style of web pages. The DOM element we get is an object (object), so it is called Document Object Model

  1. For JavaScript, in order to enable JavaScript to operate HTML, JavaScript has its own dom programming interface.
  2. For HTML, dom makes HTML form a dom tree, including documents, elements and nodes.


dom operations mainly focus on element operations, including creation, addition, deletion, modification, query, attribute operation and event operation.

6.1 creating

  1. document.write
  2. innerHTML
  3. createElement

6.2 add

  1. appendChild
  2. insertBefore

6.3 delete

  1. removeChild

6.4 modification

It mainly modifies dom element attributes, dom element contents, attributes, form values, etc

  1. Modify element attributes: src, href, title, etc
  2. Modify the contents of common elements: innerHTML, innerText
  3. Modify form elements: value, type, disabled, etc
  4. Modify element style: style, className

6.5 inspection

It mainly gets the elements of the query dom

  1. API methods provided by DOM: getElementById, getElementsByTagName , old usage is not recommended
  2. New methods provided by H5: querySelector, querySelectorAll
  3. Use node operations to obtain elements: parent node, children, and sibling

6.6 attribute operation

This is mainly for custom attributes.

  1. setAttribute: sets the attribute value of dom
  2. getAttribute: get the attribute value of dom
  3. removeAttribute remove attribute

6.7 event operation

Register the event for the element and take the {event source Event type = event handler

Keywords: Javascript

Added by flattened on Tue, 21 Dec 2021 09:34:33 +0200