JavaScript DOM of front-end web

Keywords: Attribute Javascript PHP React

JS HTML DOM

When the web page is loaded, the browser creates the document object model of the page.

With the HTML DOM, JavaScript can access and change all elements of an HTML document.

DOM document operation

Find HTML elements

Method describe Example
document.getElementById(id) Find elements by element id Find the element with id = "intro": let myElement = document.getElementById("intro");
document.getElementsByTagName(name) Find elements by tag name Find all < p > elements: myElement = document.getElementsByTagName("P");
document.getElementsByClassName(name) Find elements by class name Find the list of all elements containing class = "intro": document.getElementsByClassName("intro");
document.querySelectorAll("tag.css_name") CSS selector to find HTML elements Returns a list of all < p > elements of class = "intro": let el=document.querySelectorAll("p.intro");

For example: find the < p > label element under the element with the id of demo

<!DOCTYPE html>
<html>
    <body>
        <h1>
            demo page
        </h1>
        <div id="demo">
            <p> this is demo p tag</p>
            <p> hello demo</p>
        </div>
        <p id="message">message</p>
        <script>
            let div_tags = document.getElementById("demo")
            let p_tags = div_tags.getElementsByTagName("p")
            document.getElementById("message").innerHTML = "message is " + p_tags[0].innerHTML       
        </script>
    </body>
</html>

Change HTML elements

Method describe Example
element.innerHTML = new html content Change the inner HTML of an element Modify the content of the < p > element: document.getElementById("p_msg") = "Hello world!!";
element.attribute = new value Change the attribute value of HTML element Modify the src attribute of the < img > element: document.getElementById("image"). src = "/ i/porsche.jpg";
element.setAttribute(attribute, value) Change the attribute value of HTML element Add the name attribute to the element with id message: document.getElementById("message"). setAttribute("name", "change_attr")
element.style.property = new style Change the style of HTML elements Change the style of the < p > element: document.getElementById("message"). style.color = "blue";

Add and remove elements

Method describe
document.createElement(element) Create HTML elements
document.removeChild(element) Delete HTML element
document.appendChild(element) Add HTML element
document.replaceChild(element) Replace HTML elements
document.write(text) Write HTML output stream

Add event handler

Method describe
document.getElementById(id).onclick = function(){code} Add event handlers to onclick events

Find HTML object

HTML has a lot of properties. At this time, only a few common properties are listed

attribute Explain
document.forms Return all < form > elements
document.images Return all < img > elements
document.links Returns all \ and < a > elements that have an href attribute

For example: find the form element with id = frm1, in the forms collection, and then display all the element values

<!DOCTYPE html>
<html>
<body>

<h1>Use document.forms lookup HTML element</h1>

<form id="frm1" action="/demo/action_page.php">
  First name: <input type="text" name="fname" value="Bill"><br>
  Last name: <input type="text" name="lname" value="Gates"><br><br>
  <input type="submit" value="Submission">
</form> 

<p>Click the try button to display the value of each element in the form.</p>

<button onclick="myFunction()">Have a try</button>

<p id="demo"></p>

<script>
function myFunction() {
  let x = document.forms["frm1"];
  let text = "";
  let i;
  for (i = 0; i < x.length ;i++) {
    text += x.elements[i].value + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

Common attributes of element

Properties / methods Explain
element.innerHTML Sets or returns the contents of an element.
element.id Sets or returns the id of the element.
element.className Sets or returns the class attribute of the element.
element.tagName Returns the label name of the element.
element.style Sets or returns the style attribute of the element.
element.textContent Sets or returns the text content of the node and its descendants.
element.title Sets or returns the title property of the element.
element.attributes Returns the NamedNodeMap of the element property. The NamedNodeMap object represents an unordered collection of element attribute nodes. Nodes in the NamedNodeMap can be accessed by name or index (number).
element.getAttribute() Returns the specified attribute value of the element node.
element.getAttributeNode() Returns the specified property node.
element.getElementsByTagName() Returns a collection of all child elements that have the specified label name.
element.hasAttribute() Returns true if the element has the specified attribute, otherwise false.
element.hasAttributes() Returns true if the element has attributes, false otherwise.
element.setAttribute() Sets or changes the specified property to the specified value.
element.toString() Converts an element to a string.

For more properties, refer to: element object properties

Attribute attr object

In the HTML DOM, the attr object represents the HTML attribute.
The NamedNodeMap object represents an unordered collection of element attribute nodes.
Nodes in the NamedNodeMap can be accessed by name or index (number).
Common attribute s and operation methods:

Properties / methods Explain
attr.isId Returns true if the attribute is of id type, false otherwise.
attr.name Returns the name of the property.
attr.value Sets or returns the value of the property.
attr.specified Returns true if a property is specified, false otherwise.
nodemap.getNamedItem() Returns the specified property node from the NamedNodeMap.
nodemap.item() Returns the node in the NamedNodeMap under the specified subscript.
nodemap.length Returns the number of nodes in the NamedNodeMap.
nodemap.removeNamedItem() Removes the specified attribute node.
nodemap.setNamedItem() Sets the specified attribute node (by name).

Example:

<!DOCTYPE html>
<html>
    <body>
        <h1>
            demo page
        </h1>
        <div id="demo">
            <p> this is demo p tag</p>
            <p> hello demo</p>
        </div>
        <p id="message">message</p>
        <script>
            let div_tags = document.getElementById("demo")
            let p_tags = div_tags.getElementsByTagName("p")
            document.getElementById("message").setAttribute("name", "change_attr")
            // Returns the name and value of the property
            console.log(document.getElementById("message").attributes[1].name, 
                document.getElementById("message").attributes[1].value)
            // Returns the value of the specified property
            let el = document.getElementById("message")
            let el_map = el.attributes
            // The getNamedItem() method returns the property node with the specified name from the namedNodeMap
            console.log(el_map.getNamedItem("name").value)
            console.log(el_map.getNamedItem("name").textContent)
            // The setNamedItem() method adds the specified node to the nodeMap.
            let new_attr = document.createAttribute("class")
            new_attr.value = "test_data"
            el_map.setNamedItem(new_attr)
            console.log(el_map.getNamedItem("class").value)
        </script>
    </body>
</html>

DOM incident

DOM can use JavaScript to react to HTML events.
The Event object represents the state of the Event, such as the element in which the Event occurs, the state of the keyboard key, the position of the mouse, and the state of the mouse button.
Events are usually used in conjunction with functions, which are not executed before the event!
We can dynamically define event handler in HTML, and trigger corresponding JavaScript when conditions are met.
Common event handles are as follows:

Event Handler Explain
onclick The event handle that is called when the user clicks an object.
ondblclick The event handle that is called when the user double clicks an object.
onfocus Element gets focus.
onchange When the user changes the content of the input field. Often used in conjunction with input field validation.
onload User login page, or a page or an image to complete the loading.
onunload The user exits the page. Can be used to process cookie s.
onmouseover Mouse over an element.
onmousemove The mouse is moved.
onreset The reset button is clicked.
onselect The text is selected.
onsubmit The confirm button is clicked.
onerror An error occurred while loading the document or image.

Example:

<!DOCTYPE html>
<html>
    <body>
        <h1>
            demo page
        </h1>
        Configuration 1: <input type="text" id="f_1" value="Configuration 1">
        <br>
        Configuration 2: <input type="text" id="f_2">
        <br>
        <p>click button Replication configuration</p>
        </br>
        <br>
            <button onclick="func_copy()">copy</button>
        </br>
        <script>
            function func_copy() {
                let data = document.getElementById("f_1").value
                document.getElementById("f_2").value = data
            }
        </script>
    </body>
</html>

For more events, please refer to: Event type

DOM event listener

addEventListener() method

Attach an event handler to an element without overwriting an existing event handler; multiple listeners can be added to an event.
Usage:

element.addEventListener(event, function, useCapture);
The first parameter is the type of event (such as "click" or "mousedown").
The second parameter is the function we need to call when the event occurs.
The third parameter is a Boolean value that specifies whether to use event bubble or event capture. This parameter is optional.
Note: do not prefix events with "on"; use "click" instead of "onclick".

Example:

<!DOCTYPE html>
<html>
    <body>
        <h1>
            demo page
        </h1>
        Configuration 1: <input type="text" id="f_1" value="Configuration 1">
        <br>
        Configuration 2: <input type="text" id="f_2">
        <br>
        <p>click button Replication configuration</p>
        </br>
        <br>
            <button id="btn_1">copy</button>
        </br>
        <script>
            bt_el = document.getElementById("btn_1")
            bt_el.addEventListener("click", func_copy)
            function func_copy() {
                let data = document.getElementById("f_1").value
                document.getElementById("f_2").value = data
            }
        </script>
    </body>
</html>

Transfer parameters
When passing parameter values, you need to use anonymous functions that call the specified function as parameters

element.addEventListener("click", function(){ myFunction(p1, p2); });

Example:

<!DOCTYPE html>
<html>
    <body>
        <h1>
            demo page
        </h1>
        //Data: <input type="text" id="input_1">
        <br>
        //Data: <input type="text" id="input_2">
        <br>
            <button id="btn_1">Calculation</button>
        </br>
        <br>
        //Result: <input type="text" id="output">
        <br>
        <script>
            x = 1
            y = 3
            let bt_el = document.getElementById("btn_1");
            bt_el.addEventListener("click", function() {
                func_add(x, y);
            });
            function func_add(x, y) {
            let d1_el = document.getElementById("input_1")
            let d1 = d1_el.value
            let d2_el = document.getElementById("input_2")
            let d2 = d2_el.value
            res = d1 * x + d2 * y
            out_el = document.getElementById("output");
            out_el.setAttribute("value", res);
            };
        </script>
    </body>
</html>

Bubbling and trapping
There are two ways of event propagation in HTML DOM: bubbling and capturing.
Event propagation is a way to define the order of elements when an event occurs. If there is a < p > in the < div > element and the user clicks the < p > element, which element "click" event should be handled first?

  • In bubbling, the event of the innermost element will be processed first, and then the event of the outermost element: the click event of the < p > element will be processed first, and then the click event of the < div > element.
  • In capture, the events of the outermost element will be processed first, and then the events of the innermost element: the click events of the < div > element will be processed first, and then the click events of the < p > element.

In the addEventListener() method, specify the propagation type by using the "useCapture" parameter:

addEventListener(event, function, useCapture);
The default value is false, bubbling propagation will be used, and if the value is set to true, capture propagation will be used for the event.

removeEventListener() method

The removeEventListener() method removes event handlers that have been attached through the addEventListener() method

element.removeEventListener("mousemove", myFunction);

DOM node

With HTML DOM, you can use node relationships to navigate the node tree.

Node type

Everything in an HTML document is a node:

  • The whole document is a document node
  • Each HTML element is an element node
  • Text within an HTML element is a text node
  • Each HTML attribute is a property node
  • All comments are comment nodes

Node relationship

Nodes in a node tree have hierarchical relationships with each other. The terms (parent, child and sibling, parent, child, and sibling) are used to describe these relationships.

  • In the node tree, the top node is called the root (root node).
  • Each node has a parent, except for the root (which has no parent).
  • Nodes can have a certain number of children
  • A sibling is a node that has the same parent.

With JavaScript, you can navigate between nodes using the following node properties:

  • parentNode
  • childNodes[nodenumber]
  • firstChild
  • lastChild
  • nextSibling
  • previousSibling

Child nodes and node values

Text node
The value of the text node can be accessed through the innerHTML attribute of the node,
Accessing the innerHTML property is equivalent to accessing the nodeValue of the first child node.
Example:

<!DOCTYPE html>
<html>
    <body>
        <h1>
            demo page
        </h1>
        <p id="ps_1">hello world</p>

        <script>
            // The value of the text node can be accessed through the innerHTML attribute of the node
            data = document.getElementById("ps_1").innerHTML
            // Accessing the innerHTML property is equivalent to accessing the nodeValue of the first child node
            data_2 = document.getElementById("ps_1").childNodes[0].nodeValue
            data_3 = document.getElementById("ps_1").firstChild.nodeValue
            console.log(data)
            console.log(data_2)
            console.log(data_3)
        </script>
    </body>
</html>

nodeName property
The nodeName property specifies the name of the node.

  • nodeName is read-only
  • nodeName of element node is equivalent to label name
  • The nodeName of the attribute node is the attribute name
  • Text node nodeName always "text"
  • The nodeName of a document node is always "document"

nodeValue property
The nodeValue property specifies the value of the node.

  • nodeValue of element node is undefined
  • The nodeValue of a text node is text
  • The nodeValue of the attribute node is the attribute value

DOM node operation

Create a new HTML element (node)

To add a new element to the HTML DOM, you must first create the element (element node) and then append it to the existing element.
appendChild() method, appending the new element as the last child of the parent
Example:

<!DOCTYPE html>
<html>
    <body>
        <h1>
            demo page
        </h1>
        <div>
            <p id="ps_1">Paragraph text2</p>
            <p id="ps_1">Paragraph text1</p>
        </div>
        <script>
            let new_el = document.createElement("p") //Create elements
            let node = document.createTextNode("Text paragraph new") //Add text node
            new_el.appendChild(node)

            let div_el = document.getElementsByTagName("div")[0]
            div_el.appendChild(new_el)
        </script>
    </body>
</html>

The insertBefore(new_el, el) method inserts a new element in front of the specified element

<!DOCTYPE html>
<html>
    <body>
        <h1>
            demo page
        </h1>
        <div>
            <p id="ps_1">Paragraph text1</p>
            <p id="ps_2">Paragraph text2</p>
        </div>
        <script>
            let new_el = document.createElement("p") //Create elements
            let node = document.createTextNode("Text paragraph new") //Add text node
            new_el.appendChild(node)

            let div_el = document.getElementsByTagName("div")[0]
            div_el.insertBefore(new_el, document.getElementById("ps_2"))
        </script>
    </body>
</html>

Delete existing HTML elements

To delete an HTML element, you need to find its parent first

<!DOCTYPE html>
<html>
    <body>
        <h1>
            demo page
        </h1>
        <div>
            <p id="ps_1">Paragraph text1</p>
            <p id="ps_2">Paragraph text2</p>
        </div>
        <script>
            //Deleted child element
            let child_el = document.getElementById("ps_2");
            //Parent element of deleted child element
            let parent_el = child_el.parentElement;
            parent_el.removeChild(child_el)
        </script>
    </body>
</html>

Replace HTML elements

The replaceChild() method is used to replace the element, and the parent element of the response needs to be found

parent_el.replaceChild(new_child, old_child_el)

Example:

<!DOCTYPE html>
<html>
    <body>
        <h1>
            demo page
        </h1>
        <div>
            <p id="ps_1">Paragraph text1</p>
            <p id="ps_2">Paragraph text2</p>
        </div>
        <script>
            //New elements
            let new_child = document.createElement("p")
            let new_node = document.createTextNode("New paragraph")
            new_child.appendChild(new_node)
            //Subelement
            let old_child_el = document.getElementById("ps_2");
            //Parent element of child element
            let parent_el = child_el.parentElement;
            parent_el.replaceChild(new_child, old_child_el)
        </script>
    </body>
</html>

reference:
https://www.w3school.com.cn/js/js_htmldom_document.asp
https://www.w3school.com.cn/jsref/dom_obj_all.asp

74 original articles published, praised 12, visited 50000+
Private letter follow

Posted by onepixel on Sat, 07 Mar 2020 00:22:46 -0800