DOM Manipulation | How to get elements using ID , Class and Tags with working code and output snaps(Also covered "how to change CSS styles of different tags using JS")

 How to get elements using ID , Class and Tags in Javscript 

/*HERE IS THE CODE . JUST COPY AND PASTE IN YOUR TEXT EDITOR*/

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Test Page</title>
</head>


<body>

        <h1 class="header-tag" style="text-align:center; color:red;">EXERCISE</h1>
          <p>Lorem ipsum dolor sit amet.</p>
          <p>Lorem ipsum dolor sit amet.</p>
          <p>Lorem ipsum dolor sit amet.</p>
          <p>Lorem ipsum dolor sit amet.</p>
          <p>Lorem ipsum dolor sit amet.</p>
          <div id="alone">
            <h3>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro veniam sint doloremque, necessitatibus. Quaerat pariatur est minima unde doloremque quo rerum, consectetur officia nesciunt repellendus!</h3>
          </div>

        <button onclick="box()"> SUBMIT </button>

  <script>

/* To Change fontSize and color of H1 by using getElementsByClassName*/
      // function box(){
      //   var a = document.getElementsByClassName("header-tag");
      //   a[0].style.color="blue";
      //   a[0].style.fontSize ="42px";
      // }

/* To change the styles of individual div elements using tag "getElementsByTagName" */
      // function box(){
      //   var a = document.getElementsByTagName("p");
      //   a[0].style.color="blue";
      //   a[1].style.fontSize ="24px";
      //   a[2].style.backgroundColor ="dodgerblue";
      // }
/* To change the styles of individual div elements using tag "getElementById" */
      function box(){
        var a = document.getElementById("alone");
        a.style.backgroundColor ="dodgerblue";
      }
  </script>
</body>
</html>

HERE ARE A FEW SNAPS OF THE OUTPUT CODE :

1. "getElementById" Example.(Change of color of para on clicking the submit button) 


HOW THE OUTPUT LOOKS BEFORE CLICKING SUBMIT BUTTON:


HOW THE OUTPUT LOOKS AFTER CLICKING SUBMIT BUTTON :


2. "getElementByTagName" Example.(Change of background-color of para/div/Tag on clicking the submit button):



 
3. "getElementsByClassName" Example.(Change of background-color of para/div/Tag on clicking the submit button):


Another way of doing all the things at once is to remove all the functions and make them into a single one and change all the DOM objects to different names i.e a , b, c, etc. Output along with the code goes like this :


 

Hope you like it :) please leave comments for additional notes and any doubts!!

Comments

Popular posts from this blog