jQuery selector syntax question
Here is my html:
<form>
<dl>
<dt> </dt>
<dd><input type="hidden"></dd>
<dt>Dont hide this one</dt>
<dd><input type="text"></dd>
</dl>
</form>
I'm using jQuery to hide the dt
/dd
elements where the input type is hidden with this code:
$("input[type=hidden]").each(function() {
$(this).parent().hide().prev().hide();
});
But I also only want to apply this to dt
s where the text is
. How can I do this sort of select?
Update: Maybe I need to clarify: A few people have posted answers where it hides the dd before checking if the content of the dt is also
. Both conditions must be true before hiding both the dt and dd.
Final Solution: Here's what I ended up with:
$('input[type=hidden]').filter(function() {
return $(this).closest('dd').prev('dt').html() === ' 开发者_如何学运维;';
}).each(function() {
$(this).closest('dd').hide()
.prev('dt').hide();
});
$("input[type=hidden]").filter(function() {
return $(this).parent().prev('dt').html() === " ";
}).each(function() {
$(this).parent().hide().prev().hide();
});
This will not select <dt>foo bar</dt>
which contains(' ')
would.
More concisely (with credit to Emil's answer)
$("input[type=hidden]").filter(function() {
return $(this).closest('dd').prev('dt').html() === " ";
}).closest('dd').hide().prev('dt').hide();
Use the contains selector:
$("dt:contains(' ')").hide();
$("input[type=hidden]").each(function() {
$(this).closest('dd').hide()
.prev('dt').hide();
});
This code finds the closest parent of the input with tag dd
, hides it, then looks for a dt
sibling and hides it as well.
This also does the trick (adapted from an earlier version of cobbal's answer):
$("input[type=hidden]").each(function() {
if ($(this).parent().prev().filter(function() {
return $(this).html() === " ";
}).hide().length > 0) {
$(this).hide();
}
});
The contains selector doesn't match the whole content, so it might work for you, but is not an ideal solution. The correct way to do this is to use the filter function:
$('input[type=hidden]').filter(function() {
return $(this).prev().html() == ' '
})
.each(function() {
$(this).hide();
$(this).prev().hide();
});
精彩评论