jQuery elements with attribute greater than passed variable (.filter()) Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of jQuery elements with attribute greater than passed variable (.filter()) without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I know I can use jQuery’s .filter() for filtering by attribute. I also know that usage of such custom attributes is frowned upon since W3C’s official implementation of data-thing in HTML5.

But I still want to know why this is not working.

JS:

$("[id^=hide]").click(function() {
    var lvl = $(this).attr('lvl');
    var id = $(this).attr('tar');

    $('#' + id).slideToggle(100);

    $('div').filter(function(lvl) {
        return $('this').attr('lvl') > lvl;
    }).slideToggle(100);
});

HTML:

<a id="hide1" lvl="0" tar="1"></a>
<div id="1" lvl="0"></div>
<a id="hide2" lvl="1" tar="2"></a>
<div id="2" lvl="1"></div>
<a id="hide3" lvl="2" tar="3"></a>
<div id="3" lvl="2"></div>
<a id="hide4" lvl="2" tar="4"></a>
<div id="4" lvl="2"></div>
<a id="hide5" lvl="1" tar="5"></a>
<div id="5" lvl="1"></div>
<a id="hide7" lvl="2" tar="7"></a>
<div id="7" lvl="2"></div>

What I want to achieve is. 1. Click on the link. 2. SlideToggle the div that is close to the link. 3. SlideToggle all other divs that have level attribute bigger than level attribute of that link.

I was also trying to do it like this:

$("[id^=hide]").click(function() {
    var lvl = $(this).attr('lvl');
    var id = $(this).attr('tar');

    $('#' + id).slideToggle(100);
    hideOthers(lvl);
});

var hideOthers = function(lvl) {
    $('div').filter(function(lvl) {
        return $('this').attr('lvl')> lvl;
    }).slideToggle(100);
}

But that’s also not working. Any ideas?

Answer

Updated Fiddle

In this line on your code :

 $('div').filter(function(lvl) {

The lvl considered as index in jquery filter() function, so the value of lvl inside the function is [ 0 – 1 – 2 …. nbr_of_divs ].

to fix that just remove lvl from param and use it directly.

$('div').filter(function() {
    return $(this).attr('lvl') > lvl;
}).slideToggle(100);

Removing also apostrophes ( ‘ ) from $(this) inside filter function :

Replacing :

return $('this').attr('lvl')> lvl;

By :

return $(this).attr('lvl') > lvl;

And it work, Hope that this help.

We are here to answer your question about jQuery elements with attribute greater than passed variable (.filter()) - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji