简体   繁体   中英

set a new id for a class in javascript

I have a class as

 <div class="group-left article_left">

I need to add a id for this class dynamically using JavaScript.

i have added the following code

    var thediv = document.getElementByClass("#group-left");
     thediv.id = "pad_id";

But the id is not appearing in my code.Can anyone help me.

The method is called getElementsByClassName and returns a NodeList, not a single node (so you need to treat it as an array and either loop over it or just grab the first element from it).

You also need to spell your class name correctly. You don't have a # character in it.

 var thediv = document.getElementsByClassName("group-left")[0];
 thediv.id = "pad_id";

It isn't supported by Internet Explorer 8 or lower so you may wish to use a polyfill or a library (such as YUI or anything else implementing a selector engine ) with equivalent functionality instead.

There is now getElementsByClass method in javascript unless you use some library. You can use jquery

$('.class').attr('id','pad_id');

You should only use one id per element though. Remember that

您必须使用setAttribute ,例如:

thediv.setAttribute("id", "pad_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