Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Filter children which has a particular attribute

Tags:

jquery

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?

Update:

I am getting TypeError: $(...).data(...) is undefined

The rendered HTML is:

<li data-entityid="WF/008/DAM" class="dropdownli filterItem">&nbsp;&nbsp;&nbsp;
    <input type="checkbox" data-entityid="WF/008/DAM" value="WF/008/DAM/014" name="damBrand">
    <label>E&amp;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.

like image 442
Tapas Bose Avatar asked Dec 26 '12 08:12

Tapas Bose


People also ask

Which jQuery content filter would you use to select elements that contain certain child elements?

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.

How do we filter out elements using jQuery?

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.

What are the jQuery most basic filtering methods?

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.

Which type of parameter can jQuery filter function take?

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.


1 Answers

var selectedLis = $('ul').children('li[data-brandId]');

or with a filter:

var selectedLis = $('ul').children('li').filter(function() {
    return $(this).data('brandId');
});
like image 151
adeneo Avatar answered Nov 16 '22 00:11

adeneo