Access the HTML elements in JavaScript

JavaScript1 min read
Access the HTML elements in JavaScript
javascripthtmlweb developmentbeginner

3 most common technique for access the HTML elements in javascript: By using ID, By using class name, By CSS selector

3 most common technique for access the HTML elements in javascript

  1. By using ID: for the button element we give ID of submitBtn,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button id="submitBtn"></button> </body> </html>
  • Now we access by, document.getElementById and inside the parenthesis we write the ID name.
  • Then we set innerHTML for the button as submit, it update the button text.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button id="submitBtn"></button> <script> document.getElementById('submitBtn').innerHTML = 'Submit' </script> </body> </html>
  1. By using class name: in this div we give a class name of container.
<body> <div class="container"></div> </body>
  • Then we change the background color of this div, by using document.getElementByClassName().
<script> document.getElementsByClassName('container')[0].style.backgroundColor = 'red' </script>
  • It change the background color of the div.
  1. By CSS selector: here we have a image element in HTML.
<body> <img src="" alt=""> </body>
  • To access this we use document.querySelector().
<script> document.querySelector('img').src = 'https://image_path.jpg' </script>