Reputation: 29816
I have some li
elements among them some of the li
has an attribute data-brandId
and some of them don't have this attribute. I have the parent ul
from which I am filtering it as:
var selectedLis = new Array();
$('ul').children('li').each(function(){
if($(this).attr(attribute) != null) {
selectedLis.push($(this));
}
});
Is there any better way to achieve this; like by using filter
etc?
I am getting TypeError: $(...).data(...) is undefined
The rendered HTML is:
<li data-entityid="WF/008/DAM" class="dropdownli filterItem">
<input type="checkbox" data-entityid="WF/008/DAM" value="WF/008/DAM/014" name="damBrand">
<label>E&W Portfolio</label>
</li>
This is giving me the error:
var lis = $('ul[name=damBrandMenu]').children('li').filter(function(){
return $(this).data('entityId').length;
});
Also say I don't have the data-entityId in the li
, instead I have this attribute in the input[type="checkbox"] which is the child of li, as you can see in the HTML. Then what will be the way for filtering? Is it:
var lis = $('ul[name=damBrandMenu]').children('li').filter(function(){
return $('> input[type="checkbox"]', this).data('entityid').length;
});
I have also tried: $(this).attr('data-entityId').length;
and $('> input[type="checkbox"]', this).attr('data-entityId').length;
, but they are also not working. I am having same error; TypeError: $(...).attr(...) is undefined
.
Upvotes: 8
Views: 23067
Reputation: 904
You can simply use JQuery attribute filters for this as,
var selectedLis = $("li[data-brandId]");
Upvotes: 0
Reputation: 318252
var selectedLis = $('ul').children('li[data-brandId]');
or with a filter:
var selectedLis = $('ul').children('li').filter(function() {
return $(this).data('brandId');
});
Upvotes: 20
Reputation: 6625
var selectedLis = $('ul li').filter(function() {
return $(this).data('brandId').length;
});
Upvotes: 2
Reputation: 48793
var attribute = 'data-brandId';
var selectedLis = $('ul > li['+attribute+']');
Upvotes: 2