How can I get all <li> elements where <span class="x"> using jQuery?
How can I get all list elements having a <span>
element with class="required"
<form id="aform">
<ul>
<li id="name" >
<label class="description" for="name">Name<span class="required">*</span></label>
<div>
<input id="brand_name" name="brand_name" class="text textfield50pc" type="text" maxlength="40" value="<?php echo $brand->n开发者_JAVA百科ame; ?>"/>
</div>
</li>
</ul>
</form>
Try: $('li').has('span.required')
You can try this:
var span_required = $('li span.required');
var li_required = [];
$.each(span_required, function(index, item){
li_required[index] = $(item).parents('li').get(0);
});
Fiddle: http://jsfiddle.net/maniator/rX2jA/
var $required_items = $('li:has(span.required)');
var $required_items = $('li').has('span.required');
The latter one is probably faster: jsperf test.
$('li:has(span.required)')
http://api.jquery.com/has-selector/
You can use filter
$("li").filter(function() {
return $(this).find("span.required").length > 0
})
Or has
$("li").has("span.required")
Examples on jsFiddle
You can use this way.
$(document).ready(function (){
alert( $('span.required').parents("li").length);
})();
You could use:
var listElements = $('li').has('span.required');
JS Fiddle demo.
精彩评论