Cover Image for Javascript – document.getElementById()
301 views

Javascript – document.getElementById()

The JavaScript document.getElementById() method is used to get the element in the document with a specific ID. It returns a single element object, which is the first element in the document with the specified ID.

The getElementById() method takes an ID as its parameter and returns the element in the document with the specified ID.

The getElementById() method is called with the argument “myParagraph” to get the <p> element with the ID “myParagraph” in the document. The returned element object is then logged to the console, which will output the <p> element with the ID “myParagraph”.

Note that if there is no element in the document with the specified ID, the getElementById() method will return null. Also, each element in the document can have a unique ID, so it’s important to ensure that each ID in the document is unique.

Here is an example of how to use getElementById() method to get the <p> element with the ID “myParagraph” in an HTML document:

HTML<span role="button" tabindex="0" data-code="<html> <head> <title>Example</title> </head> <body> <p id="myParagraph">This is my paragraph.</p> <script> const paragraph = document.getElementById("myParagraph"); console.log(paragraph); // Output: <p id="myParagraph">This is my paragraph.</p> </script> </body>
<html>
<head>
  <title>Example</title>
</head>
<body>
  <p id="myParagraph">This is my paragraph.</p>
  <script>
    const paragraph = document.getElementById("myParagraph");
    console.log(paragraph); // Output: <p id="myParagraph">This is my paragraph.</p>
  </script>
</body>
</html>

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS