JavaScript get element by id value | Simple example code

  • by

You can get the element by using id, for that you have to use a getElementById method in JavaScript. But you have to define id for the specified element (field).

Note: Returns null if no elements with the specified ID exist.

Example of JavaScript get element by id

HTML example code How to Get the element with the specified ID in JavaScript:

This method is used almost every time you want to manipulate, or get info from, an element on your document. In the example, we are using it only gets an element.

<!DOCTYPE html>
<html>
<body>

    <p id="demo">Hello </p>

    <script>

      var txt = document.getElementById("demo");
      alert(txt);
      
  </script>

</body>
</html>

Output:

JavaScript get element by id value HTML

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.