DEV Community

R.Shobika CSE
R.Shobika CSE

Posted on

SELECTORS

ELEMENT SELECTORS:

In JavaScript You want to manipulate the HTML you have to find the elements first. There are several ways to do this:

  • Finding HTML elements by id

  • Finding HTML elements by tag name

  • Finding HTML elements by class name

  • Finding HTML elements by CSS selectors

  • Finding HTML elements by HTML object collections

Finding HTML elements by id

  • Its is used to find the HTML element in DOM by using id
<h1 id="name">hello<h1>
<script>
  const ele = document.getElementById("name");
  console.log(ele.innerText);
</script>
Enter fullscreen mode Exit fullscreen mode

output:
hello

Finding HTML elements by tag name

  • It is used to find HTML element in DOM by Using the Tag name
<h1 id="name">Welcome<h1>
<script>
  const ele = document.getElementByTagName("h1");
  console.log(ele[0].innerText);
</script>
Enter fullscreen mode Exit fullscreen mode

output:
Welcome

Finding HTML elements by class name

  • It is used to find HTML element in DOM by using the class name
<h1 class="name">shobika<h1>
<script>
  const ele = document.getElementByClassName("name");
  console.log(ele[0].innerText);
</script>

Enter fullscreen mode Exit fullscreen mode

output:
shobika

Finding HTML elements by CSS selectors

  • Its a Query selector method()
<h1 class="name">JavaScript<h1>
<script>
  const ele = document.querySelector(".name");
  console.log(ele.innerText);
</script>
Enter fullscreen mode Exit fullscreen mode

output:
JavaScript

Finding HTML elements by HTML object collections

  • Its a querySelectorAll() Method
<h1 class="name">JavaScript<h1>
<h1 class="name">Java<h1>
<script>
  const ele = document.querySelectorAll(".name");
  console.log(ele[1].innerText);
</script>
Enter fullscreen mode Exit fullscreen mode

output:
Java

Task 1: Disabled the button after clicking

    <button id="click" onclick="Clicking()">click me!</button>
    <script>
        function Clicking(){
            const select = document.getElementById("click")
            if(select.disabled==false){
                select.disabled=true;
            }

        }
    </script>
Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)