user2659948
user2659948

Reputation: 45

how to add class to element from its id?

For some reason I can't set class of this element directly in class (a script somehow overrides it), so I want to do it on window load, by reading id and placing it as class. I want to get something like this:

<div id="mask" class="picture"></div>

<script>
window.onload = function(){
   $( "div.picture" ).addClass( $(this).attr('id'));
}
</script>

But this obviously does not work. Any help?

Upvotes: 3

Views: 31

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

You can make use of the callBack function of addClass at this context,

$( "div.picture" ).addClass(function(){ return this.id; });

Upvotes: 1

Pavan Teja
Pavan Teja

Reputation: 3202

try this in onload.in the question you are using $(this).attr() but actually you dont have that element reference in pageload.you have to loop over all the elements matched by Jquery selector and inside you can access each using $(this)

   $( "div.picture" ).each(function(){
     $(this).addClass( $(this).attr('id'));
   })

Upvotes: 2

Related Questions