DEV Community

Sasireka
Sasireka

Posted on

DOM in JS

1)What is DOM?

  • DOM allows javascript to dynamically manipulate HTML elements and styles on a webpage.

  • DOM is a programming interface that represents HTML as objects so javascript can manipulate them.

2)How to find HTML elements?

  • Javascript finds HTML element using DOM methods.

  • DOM methods:

    • getElementById
    • getElementsByClassName
    • getElementsByTagName
    • querySelector
    • querySelectorAll

getElementById

  • It selects a single element using its unique id.

  • Example:

<h1 id="one">Hello</h1>
<script>
   const element = document.getElementById("one");
   console.log(element)
</script>
Enter fullscreen mode Exit fullscreen mode

//output: <h1 id="one">Hello</h1>

getElementsByClassName

  • It selects all elements with the given class name.

  • Example:

<h1 class="one">Hello</h1>
<h1 class="one">Hii</h1>
<h1 class="one">Welcome</h1>
<script>
   const element = document.getElementsByClassName("one");
   console.log(element)
</script>
Enter fullscreen mode Exit fullscreen mode

//output: HTMLCollection(3) [h1.one,h1.one,h1.one]

getElementsByTagName

  • It selects all elements with the given tag name.

  • Example:

<p>Welcome</p>
<p>Hello</p>
<script>
   const element = document.getElementsByTagName("p");
   console.log(element[0])
</script>
Enter fullscreen mode Exit fullscreen mode

//output: <p>Welcome</p>

querySelector

  • It selects the first element that matches a css selector.

  • Example:

<h1 class="one">Hello</h1>
<h1 class="one">Hii</h1>
<h1 class="one">Welcome</h1>
<script>
   const element = document.querySelector(".one");
   console.log(element)
</script>
Enter fullscreen mode Exit fullscreen mode

//output: <h1 class="one">Hello</h1>

querySelectorAll

  • It selects all the elements that matches a css selector.

  • Example:

<h1 class="one">Hello</h1>
<h1 class="one">Hii</h1>
<h1 class="one">Welcome</h1>
<script>
   const element = document.querySelectorAll(".one");
   console.log(element)
</script>
Enter fullscreen mode Exit fullscreen mode

//output: NodeList(3) [h1.one,h1.one,h1.one]

Top comments (0)