Sunday 30 September 2018

JavaScript: getElementsByTagName: Get elements by tag name

getElementsByTagName return all the elements with given tag name

Syntax
element.getElementsByTagName(tagName);

Ex:
document.getElementsByTagName("li");

Above statement return all the elements with tag name li.

getElesByTagName.html
<!DOCTYPE html>

<html>

<head>
    <title>Get Element By tag name</title>
</head>

<body>
    <h1>Countries in Asia</h1>

    <ol id="countriesInAsia">
        <li>India</li>
        <li>Indonesia</li>
        <li>Iran</li>
        <li>Iraq</li>
        <li>Israel</li>
    </ol>

    <h1 id="countriesInEurope">Countries in Europe</h1>
    <ol>
        <li>Albania</li>
        <li>Andorra</li>
        <li>Armenia</li>
        <li>Austria</li>
        <li>Azerbaijan</li>
    </ol>

    <script>
        var countries = document.getElementsByTagName("li");

        for (var i = 0; i < countries.length; i++) {
            alert(countries[i].textContent);
        }
    </script>
</body>

</html>

Open above page in browser, it shows every country in the alert box.

var countries = document.getElementsByTagName("li");
                          
Above statement return all the li element in the document.

for(var i = 0; i < countries.length; i++){
         alert(countries[i].textContent);
}

Above snippet traverse through the array and print the text content in list item.

What if you want to display only list of countries in Asia?
Use following script, to get only the countries in Asia. First I am getting the element where id is "countriesInAsia", Next I
queried on countriesInAsia element (not on document element).

<script>
         var countriesInAsia = document.getElementById("countriesInAsia");
         var countries = countriesInAsia.getElementsByTagName("li");
                          
         for(var i = 0; i < countries.length; i++){
                  alert(countries[i].textContent);
         }

</script>





Previous                                                 Next                                                 Home

No comments:

Post a Comment