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
.
nth-of-type() Selector: This selector is used to select all elements that are the nth-child of their parent in relation to siblings with the same element name. only-child Selector: This selector is used to select all elements that are the only child of their parent.
jQuery filter() Method The filter() method returns elements that match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.
The most basic filtering methods are first() , last() and eq() , which allow you to select a specific element based on its position in a group of elements.
The jQuery filter() method can take the selector or a function as its argument to filters the set of matched elements based on a specific criteria.
var selectedLis = $('ul').children('li[data-brandId]');
or with a filter:
var selectedLis = $('ul').children('li').filter(function() {
return $(this).data('brandId');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With