Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

class

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

like image 886
Eugene Avatar asked Nov 28 '09 15:11

Eugene


People also ask

How can give multiple CSS properties in jQuery?

Apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call. Here you can pass key as property and val as its value as described above.

Which CSS manipulation method is used to add one or more classes to the selected elements?

addClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements. css() - Sets or returns the style attribute.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


2 Answers

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.

like image 83
Vincent Ramdhanie Avatar answered Sep 22 '22 01:09

Vincent Ramdhanie


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');
});
like image 22
Guffa Avatar answered Sep 20 '22 01:09

Guffa