Haradzieniec Haradzieniec - 6 months ago 11
jQuery Question

jquery: apply jquery .css rule if a child with a proper name exists

OK, I want to set margin for the second div on the page using

$('div#superid:nth-child(2)').css('margin-left', '10px');


Everything works find, I've reached the goal. But, I want that rule applied ONLY if this div contains at least one input radio with name superchild.
So, the rule above should apply to:

<div id="superid">
<div>some text
</div>
<div>
<input type="radio" name="superchild" value="2010">
<input type="radio" name="superchild" value="2010">
</div>
</div>


because it has at least one input radio with
name="superchild"

What's the best way to do that?

Answer

You could also use the filter method. The script below selects every div in the #superid-div, which has at least one input field of type radio and name superchild. Then it adds the desired css to the selected divs.

$('div#superid > div').filter( function(index,elem) {
    return $(this).find('input[type=radio][name=superchild]').length > 0;
}).css('margin-left', '10px');

jsFiddle

If you want do add this style ONLY to the second div, use your selector instead. But I thought my script covers the desired behaviour better.

Comments