Selecting Elements in DOM

Selecting Elements in DOM

  • getElementById() – select an element by id.
  • getElementsByName() – select elements by name.
  • getElementsByTagName() – select elements by a tag name.
  • getElementsByClassName() – select elements by one or more class names.
  • querySelector() and querySelectorAll – select elements by CSS selectors.

Note that the getElementById() and querySelector() returns an object with the Element type while getElementsByTagName() or querySelectorAll() returns NodeList which is a collection of nodes.

  1. getElementById()-returns an Element object

Syntax

let element = document.getElementById(id);

Example

<html>

    <head></head>

  <body>

   <h1 id=”demo”>Heading 1</h1>

  <script>

  const value = document.getElementById(‘demo’);

           console.log(value);

     </script>

   </body>

</html>

  1. getElementsByName() – returns a live NodeList of elements.

Syntax

let elements = document.getElementsByName(name);

Example

    <body>

        <h1 name=”demo”>Heading 1</h1>

            <script>

                        const value = document.getElementsByName(‘demo’);

                        console.log(value);

            </script>

                  </body>

  1. getElementsByTagName()- returns HTMLCollection of elements with the matching tag name in the order which they appear in the document.

Syntax

let elements = document.getElementsByTagName(tagName);

Example

 <body>

            <h1>Heading 1</h1>

            <h1>Another Heading 1</h1>

  <script>

            const value = document.getElementsByTagName(‘h1’);

            console.log(value);

  </script>

</body>

  1. getElementsByClassName() – It is an array-like object that returns only matching elements

Same as getElementById() just replace id with class

  1. querySelector() and queryselectorAll() – returns a static NodeList of elements

The querySelector() allows you to find the first element  and querySelectorAll() method to find all elements that match a CSS selector or a group of CSS selector.

             Syntax

    •  let element = parentNode.querySelector(selector);
    •  let elementList = parentNode.querySelectorAll(selector);

      Example

                <body>

                         <h1 class=”de”>Heading 1</h1>

                        <h1>Another Heading 1</h1>

                        <p>Paragraph</p>

            <script>

                        let element = document.querySelector(‘*’);

                        //let elements = document.querySelectorAll(‘*’);

                        console.log(element);

                        console.log(elements);

            </script>    </body>

Post Your Comments & Reviews

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

*

*