Best Website-BuildersBest Website-Builders
    What's Hot

    XXXTentacion: Three men found guilty of murdering rapper in 2018

    March 20, 2023

    American aid worker kidnapped in West Africa released after 6 years, officials say

    March 20, 2023

    Nursing union accepts Scottish government pay offer

    March 20, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      8 semantic HTML tags to make your website accessible, clean and modern

      March 20, 2023

      CSS Entertainment (CSSE) and Allen Media Group join Redbox as partners

      March 20, 2023

      European Bank Bonds, Stocks Fall After Surprise AT1 Wipeout of CS

      March 20, 2023

      UK banks hit as CS AT1 bond writedown sparks turmoil

      March 20, 2023

      NATIONAL VISION HOLDINGS, INC. (NASDAQ: EYE) Shareholder Class Action Alert: Bernstein Liebhard … | Business News

      March 20, 2023
    • Joomla

      How Superior Web Hosting Support Can Drive Business Success

      March 17, 2023

      PANDACU Studio Website Development Cooperation First Page Sage SEO Dsign Chicago adstargets Cardinal Digital Agency

      March 16, 2023

      Bluehost Review: Best Solution for Your Web Hosting Needs? – WISH-TV | Indianapolis News | Indiana Weather

      March 15, 2023

      What’s New in Search? SEO Strategies for 2023

      March 15, 2023

      What’s New in Search? SEO Strategies for 2023

      March 15, 2023
    • PHP

      Christina Ricci said she was nearly sued for a sex scene

      March 20, 2023

      Gen Z adults pay rent with credit cards

      March 20, 2023

      Adam Sandler Wins Mark Twain Award for American Humor

      March 20, 2023

      Sarah Snook was told the ‘inheritance’ was over

      March 20, 2023

      Anna Marie Tendler responds to Taylor Swift backlash

      March 20, 2023
    • UX

      Twitter now auto-replies to press emails with poop emoji: NPR

      March 20, 2023

      SiteSeer Technologies Expands Support Team, Enhances User Experience

      March 20, 2023

      SAP is the leader in procurement applications

      March 20, 2023

      The Future of Customer Engagement

      March 20, 2023

      Quantabio Adds Powerful Bead Booster Chemistry to Ultrafast sparQ RNA-Seq HMR Kits

      March 20, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Using a fake Samsung SSD can make upgrading your PC or PS5 difficult

      March 20, 2023

      This cybercriminal group will go to great lengths to extort money using your personal data

      March 20, 2023

      Diablo 4 patch addresses biggest beta issue

      March 20, 2023

      Realization of a robust network for the Beyond 5G/6G era

      March 20, 2023

      Satellite communications could be on more new phones and that would be great

      March 20, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » How to traverse the DOM using JavaScript
    JavaScript

    How to traverse the DOM using JavaScript

    websitebuildersnowBy websitebuildersnowOctober 30, 2022No Comments6 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    Understanding the DOM is essential in your web development career. I need to know how to select different elements in the DOM. You can then read or modify their contents.


    DOM traversal describes how to navigate the tree-like structure that an HTML document produces. Here’s a complete guide on how to traverse the DOM using JavaScript.


    What is DOM traversal?

    The Document Object Model, or DOM for short, is a tree-like representation of an HTML document. It provides an API that allows web developers to interact with her website using JavaScript.

    All items in the DOM are called nodes. You can manipulate the structure, content, and style of HTML documents only through the DOM.

    DOM traversal (also known as walking or navigating the DOM) is the act of selecting nodes in the DOM tree from other nodes. You’re probably already familiar with some of the ways to access elements in the DOM tree by ID, class, or tag name.You can use a method like document. querySelector() and document. getElementById() to do so.

    There are other methods that can be used in combination to navigate the DOM in a more efficient and robust way. As you can imagine, searching from a known point on the map is better than doing a full search.

    For example, selecting a child element from a parent element is easier and more efficient than searching through the tree.

    Sample document to traverse

    Once you have access to a particular node in the DOM tree, you can access related nodes in various ways. You can move down, up, or sideways in the DOM tree from the selected node.

    The first method searches for elements starting at the top node (such as the document node) and working downwards.

    The second method is the opposite. Search the outer element by traversing up the tree from the inner element. The last way is if you want to find an element from another element at the same level (meaning the two elements are siblings) in the document tree.

    As an example, consider the following example HTML document:

     <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Sample page</title>
    </head>
     
    <body>
    <main>
        <h1>My Page Title</h1>
        <p>Nice caption goes here</p>
     
        <article class="first__article">
            <h2>List of amazing fruits</h2>
            <p>Must eat fruits</p>
     
            <div class="wrapper-1">
                <ul class="apple-list">
                    <li class="apple">Apples</li>
                    <li class="orange">Oranges</li>
                    <li class="avocado">Avocados</li>
                    <li class="grape">
                        Grapes
     
                        <ul>
                            <li class="type-1">Moon drops</li>
                            <li>Sultana</li>
                            <li>Concord</li>
                            <li>Crimson Seedless</li>
                        </ul>
                    </li>
                    <li class="banana">Bananas</li>
                </ul>
     
                <button class="btn-1">Read full list</button>
            </div>
        </article>
     
        <article class="second__article">
            <h2>Amazing places in Kenya</h2>
            <p>Must visit places in Kenya</p>
     
            <div class="wrapper-2">
                <ul class="places-list">
                    <li>Maasai Mara</li>
                    <li>Diani Beach</li>
                    <li>Watamu Beach</li>
                    <li>Amboseli national park</li>
                    <li>Lake Nakuru</li>
                </ul>
     
                <button class="btn-2">Read full list</button>
            </div>
        </article>
    </main>
    </body>
     
    </html>

    Traverse the DOM downwards

    You can traverse downwards through the DOM using one of two methods. The first is the general selector method (element. querySelector again element. querySelectorAll).Second, you child again child node property. Besides, he has two special properties. last child and first child.

    Using selector methods

    You can use the querySelector() method to find one or more elements that match a given selector. For example, you can use the following to find the first element with a class of “first-article”: document.querySelector(‘.first-article’). and to get all h2 Elements in the document include querySelectorAll Method: document.querySelectorAll(‘h2’). of querySelectorAll The method returns a node list of matching elements. You can select each item using bracket notation.

     const headings = document.querySelectorAll('h2');
    const firstHeading = headings[0];
    const secondHeading = headings[1];

    The main caveat when using selector methods is that you should use the appropriate symbol where applicable before the selector, just like you do in CSS. For example, class is “.classname” and ID is “#id”.

    Note that the result will be an HTML element, not just the inner content of the selected element.To access the content, the node’s Inner HTML property:

     document.querySelector('.orange').innerHTML 

    Using the children or childNodes property

    of child The property selects all immediate child elements of a particular element.Here is an example child Actual properties:

     const appleList = document.querySelector('.apple-list');
    const apples = appleList.children;
    console.log(apples);

    logging apple Display in the console the set of all list items directly under the element with the “apple-list” class as an HTML collection. HTML collections are array-like objects, so you can select items using bracket notation, similar to querySelectorAll.

    Unlike child property, child node Returns all direct child nodes, not just child elements. If you are only interested in child elements, e.g. list items only, child property.

    Using special lastChild and firstChild properties

    These two methods are not as robust as the first two methods. As their name suggests, last child and first child The property returns the last and first child nodes of the element.

     const appleList = document.querySelector('.apple-list');
    const firstChild = appleList.firstChild;
    const lastChild = appleList.lastChild;

    Traverse up the DOM

    can be used to move up the DOM. parent element (again parent node) and the nearest properties.

    Using parentElement or parentNode

    both parent element again parent node The property allows you to select the parent node of the selected element up one level. The crucial difference is parent element Selects only parent nodes that are elements. on the other hand, parent node You can select the parent whether it is an element or another node type.

    In the code sample below, parent element To select the div with class “wrapper-1” from “apple-list”:

     const appleList = document.querySelector('.apple-list');
    const parentDiv = appleList.parentElement;
    console.log(parentDiv);

    Using closest properties

    of the nearest The property selects the first parent element that matches the specified selector. You can select multiple levels instead of just one. For example, if you already have a button with class “btn-1” selected, major elements that use the nearest Properties are:

     const btn1 = document.querySelector('.btn-1');
    const mainEl = btn1.closest('main');
    console.log(mainEl);

    like query selector and querySelectorAllUse the appropriate selector in the . the nearest Method.

    Traverse the DOM horizontally

    There are two ways to move horizontally through the DOM.can be used nextElement Siblings again previous element sibling. use nextElement Siblings select the next sibling element, previous element sibling Select the previous sibling.

     const orange = document.querySelector('.orange');
    const apple = orange.previousElementSibling;
    const avocado = orange.nextElementSibling;

    There is also an equivalent next brother and ex brother Properties to select from all node types, not just elements.

    Chain DOM traversal properties and methods to do more

    All the above methods and properties allow you to select any node in the DOM. However, in some cases it’s better to move up first and then down or sideways. In that case, chaining different properties can be useful.



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleSaints Report: Johnny Sticks to CSS Football – Duluth News Tribune
    Next Article Design & UX jobs | Design & UX jobs at eBay
    websitebuildersnow
    • Website

    Related Posts

    Who is EMRO | 2nd High-Level Interregional Conference on Refugee and Migrant Health | News

    March 19, 2023

    Build in 60 Seconds: How long it took GPT-4 to generate a Pong game in JavaScript

    March 18, 2023

    Learning JavaScript from ChatGPT. TL;DR — Great, but Can’t Replace Expert… | by Eric Elliott | JavaScript Scene | Mar, 2023

    March 17, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    XXXTentacion: Three men found guilty of murdering rapper in 2018

    March 20, 2023

    American aid worker kidnapped in West Africa released after 6 years, officials say

    March 20, 2023

    Nursing union accepts Scottish government pay offer

    March 20, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.