Working with the DOM tree. JS examples open

Working with the DOM tree. JS examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: ES6

Search for elements on a page:

document.getElementById('elementid')//selects an element whose id attribute is equal to elementid, if there is no element with such an id, then null is returned

document.getElementsByTagName('elementtag')//selects all elements whose tag is equal to element tag

document.getElementsByClassName('elementclass')//selects all elements that have class value

document.getElementsByClassName("article")[0];//get only the first element

document.querySelector('#playground')//selects the first element that matches the css selector
document.querySelector('h1')
document.querySelector('input')
document.querySelector(".annotation p")

document.querySelectorAll('#playground')//selects all elements that match the css selector, returns a pseudo-array
document.querySelectorAll('h1')
document.querySelectorAll('input')
document.querySelectorAll(".annotation p")

Get the element text:

var element = document.querySelector('h1');
console.log(element.innerText);

 

Document object

The document object allows you to access certain elements of a web page through properties:

document.documentElement //provides access to the root <html> element

document.body //provides access to the <body> element on a web page

document.images //contains a collection of all image objects (img elements)

document.links //contains a collection of links - <a> and <area> elements that have the href attribute defined

document.anchors //provides access to a collection of <a> elements that have a name attribute defined

document.forms//contains a collection of all forms on the web page

 

Navigating the DOM

Each individual object, whether it’s an HTML element, its attribute, or text, is represented in the DOM by a Node object. This object provides a number of properties with which we can get information about this node.

element.childNodes//contains a collection of child nodes

element.firstChild//returns the first child node of the current node

element.lastChild//returns the last child node of the current node

element.previousSibling//returns the previous element that is on the same level as the current one

element.nextSibling//returns the next element that is on the same level as the current one

element.ownerDocument//returns the root node of the document

element.parentNode//returns the element that contains the current node

element.nodeName//returns the node name

element.nodeType//returns the node type as a number

element.nodeValue//returns or sets the value of the node as plain text

element.nextElementSibling//returns the element immediately following the specified one in its parent's children list, or null

Consider an example:

<html>

<head>
    <meta charset="utf-8" />
</head>

<body>
    <div class="article">
        <h3>Page title</h3>
        <p>First p</p>
        <p>Secont p</p>
    </div>
<script>
        var articleDiv = document.querySelector("div.article");
        var nodes = articleDiv.childNodes;
        for (var i = 0; i < nodes.length; i++) {

            var type = "";
            if (nodes[i].nodeType === 1)
                type = "element";
            else if (nodes[i].nodeType === 2)
                type = "atribute";
            else if (nodes[i].nodeType === 3)
                type = "Text";

            console.log(nodes[i].nodeName + ": " + type);
        }
    </script>
</body>

</html>

Using the document.querySelector(“div.article”) method, we select the div element with the article class and iterate over it child nodes. In the loop we display the node name and its type using the nodeName and nodeType properties. Each type corresponds certain number:

element – NodeType 1
attribute – NodeType 2
text – NodeType 3

But despite the fact that there are only three nodes in the div block on the page: h3 and 2 paragraphs, the console will display seven nodes for us.

The point is that spaces between nodes are also counted as separate text nodes.

The nextSibling and previousSibling properties can also be used to iterate through the nodes in forward or backward order.

<html>

<head>
    <meta charset="utf-8" />
</head>

<body>
    <div class="article">
        <h3>Page title</h3>
        <p>First p</p>
        <p>Secont p</p>
    </div>
    <script>
        var articleDiv = document.querySelector("div.article");

        // получаем первый дочерний элемент
        var node = articleDiv.firstChild;
        // access the next node while it is defined
        while ((node = node.nextSibling) !== null) {//we turn to the next node, which is on the same level as the current one
            console.log(node.nodeName);
        }
    </script>   
</body>

</html>

 

Creating elements

The document object has the following methods to create elements:

    document.createElement("div")//creates an html element whose tag is passed as a parameter.  
    document.createTextNode("Text");//creates a text node. The node text is passed as a parameter.

After creating the elements, they must be added to the page:

    div.appendChild(elem)//adds a new elem node to the end of the collection of child nodes
    div.insertBefore(elem, referenceNode)//adds a new elem node before the referenceNode node

Now consider how to add a similar element to the beginning of the collection of child nodes of the div block:

    var articleDiv = document.querySelector("div.article");
    // create element
    var elem = document.createElement("h2");
    // create text for it
    var elemText = document.createTextNode("Hello world");
    // add text to an element as a child element
    elem.appendChild(elemText);
    // get the first element to be added before
    var firstElem = articleDiv.firstChild.nextSibling;
    // add an element to the div before the first node
    articleDiv.insertBefore(elem, firstElem);

 

Copying elements

To copy existing nodes from a Node object, you can use the cloneNode() method:

    div.cloneNode(true);

Consider an example:

    var articleDiv = document.querySelector("div.article");
    var newdiv = articleDiv.cloneNode(true);// clone the div element
    document.body.appendChild(newArticleDiv);// add to the end of the body element

true – the element will be copied with all child nodes
false – copied without child nodes

 

Delete an item

To remove an element, the removeChild() method of the Node object is called. This method removes one of the child nodes:

    div.removeChild(removableNode);

For example:

    var div = document.querySelector("div.article");
    var removableNode = document.querySelectorAll("div.article p")[0];// find the node to be deleted - the first paragraph    
    div.removeChild(removableNode);// remove the node

 

Element replacement

To replace an element, use the replaceChild(newNode, oldNode) method of the Node object.

    div.replaceChild(newNode, oldNode);//newNod - new element, oldNode - old element

For example:

<script>
    var articleDiv = document.querySelector("div.article");
    // find the node to be replaced - the first paragraph

    var oldNode = document.querySelectorAll("div.article p")[0];
    
    // create element
    var newNode = document.createElement("h2");
    
    // create text for it
    var elemText = document.createTextNode("Hello world");

    // add text to an element as a child element
    newNode.appendChild(elemText);

    // add text to an element as a child element
    articleDiv.replaceChild(newNode, oldNode);
</script>

 

Control elements

In addition to the methods and properties of the Node object in JavaScript, we can use the properties and methods of the Element objects.

Element objects are actually the same nodes – Node objects whose node type (nodeType property) is 1.

    element.tagName //returns the element tag

    element.innerText //gets or sets the text content of an element

    element.innerHTML//gets or sets the html code of the element

    element.getAttribute(attr)//returns the value of the attribute

    element.setAttribute(attr, value)//sets the attr attribute to value. If the attribute does not exist, then it is added.

    element.removeAttribute(attr)//removes the attr attribute and its value

    element.offsetWidth//element width in pixels (including border)

    element.offsetHeight//element height in pixels (including border)

    element.clientWidth//element width in pixels (no border)

    element.clientHeight//element height in pixels (no border)

    element.getBoundingClientRect()//returns an object with top, bottom, left, right properties that indicate the offset of the element relative to the top left corner of the browser

the innerText property is much like the textContent property

Read also:

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation