DEV Community

Cover image for DOM guide for beginners #3
Himanshupal0001
Himanshupal0001

Posted on

DOM guide for beginners #3

Image description

Things you must know

Parent -> Parent is the head of family. It simple words its the root of html. Html tag is the parent of html document.

Although html tag is parent of the html document but body tag is consider to be the parent. Because all the structural information of the website is in the body tag

Children -> All the tag and text in the body tags are children.

Topic to Cover

  1. How to select list of children in body tag
  2. Create element in html via js and append data into it.
  3. How to select child and element child
  4. How to select siblings

How to select list of children in body tag

As I told earlier everything in body tag is children. So first thing we want to know the list of all the children in the DOM.

HTML

<body>
    <p id="firstId">firstpera</p>
    <p class="peraclass1">pera 1</p>
    <p class="peraclass2">Pera2</p>
    <p class="peraclass3">Pera 3</p>

    <ul>
        <li class="listclass1">list1</li>
        <li class="listclass2">list2</li>
        <li class="listclass3">list3</li>
    </ul>
</body>

<!------       Script ------------->

<script>
        let child = document.body.children;
        console.log(child);
</script>
Enter fullscreen mode Exit fullscreen mode

The above code will give the list of all children in the body.

Create element in html via js and append data into it

Here we'll see how to create element in html via js and append data into it.

 //adding new child using in html from jsg
        let para = document.createElement('p');
        let textNode = document.createTextNode("This is new pera 
        from js --->pera");
        para.appendChild(textNode);
        console.log(para); //can't see the pera in body of html

//to see the eleemnt in body of html we need to append it to  body of document
        document.body.appendChild(para);

Enter fullscreen mode Exit fullscreen mode

How to select child and element child

//access first and last child of document
        let getlist = document.querySelector('ul');

        console.log(getlist.firstChild);//this will return #text
        console.log(getlist.lastChild);// this also will  return #text

        console.log(getlist.firstElementChild);//this will return first class child of ul list
        console.log(getlist.lastElementChild);//this will return last class child of ul list

Enter fullscreen mode Exit fullscreen mode

How to select siblings

let firstsibling = firstId.nextElementSibling;
        console.log(firstsibling);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)