简体   繁体   中英

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>

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 ...

try to use jquery for this. it will work as you need.

$(".classtext").each(function(){
    if($(this).html() == 'text to add id')
    {
       $(this).attr("id", "first_id");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM