Sunday 30 September 2018

JavaScript: getElemenyById: Target element by id

By using getElementById method, you can target an element with given id.

Syntax
document.getElementById(id);

getEleById.html
<!DOCTYPE html>

<html>

<head>
    <title>Get Element By Id</title>
</head>

<body>
    <p id="para1">
        Paragraph1
    </p>

    <p id="para2">
        Paragraph2
    </p>

    <script>
        var para1 = document.getElementById("para1");
        var para2 = document.getElementById("para2");

        alert(para1.textContent);
        alert(para2.textContent);
    </script>
</body>

</html>

Open above page in browser, you can able to see two alert boxes with the content in paragraphs. ‘textContent’ property returns the textual content of a node and its descendants.






Previous                                                 Next                                                 Home

No comments:

Post a Comment