Haradzieniec Haradzieniec - 1 year ago 63
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
<input type="radio" name="superchild" value="2010">
<input type="radio" name="superchild" value="2010">

because it has at least one input radio with

What's the best way to do that?

Answer Source

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');


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download