Search code examples
javascriptclassvalidationadditioninnerhtml

How do I create ID on a class HTML element on specific InnerHTML has no ID, with JavaScript?


I have a problem with a code that can not run, I want a list that share the same class add a specific id for specific text.

I have this so far can not make it work.

js

function Check() {
    var x = new Array(); x[0] = "text to add id";
    if (document.getElementsByClassName("classtext").innerHTML == x[0]) {
        x.setAttribute("id", "first_id");} else{x.setAttribute("id", "Second_id");
    }
}

html

<blink>
    <html>
        <head>
        </head>
        <body>
            <div class="classtext">text normal second id</div>
            <div class="classtext">text to add id</div>
            <div class="classtext">text normal second id</div>
            <div class="classtext">text normal second id</div>
            <span onclick="Check()">Compare</span>
        </body>
    </html>
</blink>

Solution

  • The method document.getElementsByClassName("classtext") will return an array of elements. So you can't access any property of them, you have to iterate over them first.

    Next, your declaring an array x and trying to set an HTML attribute on that, I think that's a typo.

     var elems = document.getElementsByClassName("classtext");
    
     for ( var n = 0; n < elems.length; n++ )
     {
        if (elems[n].innerHTML == x[0]) {
              elems[n].setAttribute("id", "first_id");
        } 
        else {
              elems[n].setAttribute("id", "Second_id");
        }
     }
    

    This might technicall work, BUT it will render elements with the same ID (Second_id). As per definition any id must be unique, which isn't the cas in this example. This will result in arbitrary results later ...