Eugene
Eugene

Reputation: 4337

jquery: get elements by class name and add css to each of them

I have a certain number of div boxes that all have the same class name. I am trying to apply something to them all but have no luck. The code I constructed so far is

$(document).ready(function(){
    elements = $('div.easy_editor');
    elements.each(function() { $(this).css("border","9px solid red"); });
    //elements[0].css("border","9px solid red");
});

Could you please tell me what I am doing wrong

Upvotes: 22

Views: 112061

Answers (2)

Guffa
Guffa

Reputation: 700850

What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.

There is also a shorter form for $(document).ready(function(){...}) in $(function(){...}).

So, this is all you need:

$(function(){
  $('div.easy_editor').css('border','9px solid red');
});

If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:

$(function(){
  $('.easy_editor').css('border','9px solid red');
});

Upvotes: 7

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103155

You can try this

 $('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});

The $('div.easy_editor') refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.

Upvotes: 42

Related Questions