HuekoMundo
HuekoMundo

Reputation: 59

select elements which have a special css attribute with jquery

I have the following structure:

<div class="main">
   <div class="submain">
      .....
      <div class="sub..submain">
      </div>
      .....
   </div>
   <div class="submain">
   </div>
</div>

Some of the subelements have the css property float:right;, and I dont know how many levels there are. How can I select all elements with this css property using the selector $('.main')? I have an idea, but I am trying to find an easier way to do it:

var elemsArray=[];
   function findNeededChildren(elem){
      var hasChildren = elem.children().length>0?true:false;
      if(hasChildren ){
            $.each(elem.children(),function(){
            if($(this).css('float')=='right')elemsArray.push($(this));
            findNeededChildren($(this));
      });
   }
}
findNeededChildren($('.main'));

Upvotes: 1

Views: 129

Answers (2)

Gurminder Singh
Gurminder Singh

Reputation: 1755

You can do something like

$(document).ready(function(){
   $(".main").find("div").each(function(){
     if($(this).css("float") == "right") {
      // This is the required div
     }
   });
})

And if you don't know that children of .main are divs or other tags then use

$(document).ready(function(){
   $(".main").children().each(function(){
     if($(this).css("float") == "right") {
      // This is the required element with float: right property
     }
   });
})

Upvotes: 0

Tomke
Tomke

Reputation: 38

You can select elements by an attribute, so you could try

$('div[style="float:right"]')

This should select all the divs with that attribute. But I am not sure if it will also select something with more than this one style.


Edit:

I just remembered that some people here where I work use classes for this sort of thing. It makes maintainability easier. Make a css rule that says:

.floatRight { float:right }

Then just assign this class to everything that needs floating. These should be even easier to select.

Upvotes: 1

Related Questions