coding180 icon
Coding180
get element by id JavaScript

get element by id JavaScript

Home > Tutorials > JavaScript > DOM Manipulation


After learning HTML/CSS styles, we all know that web pages organize information by tags, and the id attribute value of tags is unique, just like each person has an ID number, as long as the ID number is used to find the corresponding people. 

Then in the web page, we first find the tag through the id, and then perform the operation.

Syntax:

document.getElementById("id")

Take a look at the following code:

<!DOCTYPE HTML>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>document.getElementById - robort </title>

</head>

<body>
    <h3>Hello</h3>
    <p id="nameId">Robort</p>

    <script type="text/javascript">
        // refrence the name using its id
        var nme = document.getElementById('nameId');
        // output content from p tag
        document.write("My name is: " + nme.textContent); 
    </script>
</body>

</html>

Result:

Note: The obtained element is an object. If we want to operate on the element, we need to use its properties or methods. Here we used textContent property to get the text in p tag.

Task - Exercise 17

  1. Complete the code in line 17 to reference the p tag.
  2. Complete the code in line 18 to output the content of p tag.

Task Code

<!DOCTYPE HTML>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>document.getElementById - coding180</title>

</head>

<body>
    <h3>Hello</h3>
    <p id="js">I love javascript</p>

    <script type="text/javascript">
        var js = ;
        document.write("Js content: " + js); // output the P tag.
    </script>
</body>

</html>

 


user

Robort Gabriel

Lagos, Nigeria

Freelance Web Developer, Native Android Developer, and Coding Tutor.

Skills
  • UI / UX
  • JavaScript
  • Python
  • PHP
  • Kotlin
  • Java
  • Bootrap
  • Android
  • Laravel