I am currently trying to fetch a list of id's and exclude some specific values from that list after it has been fetched.
The fetching part seems to be no problem since it returns me a list of all the available id's, however i am struggling with excluding some particular values from the fetched list.
I tried using the JQuery not Selector in two different ways. In the first example i am trying to fetch a list of id's and exclude the id 011 directly from the data attribute. In the second example i am fetching the list and excluding the value afterwards using another variable.
const hourID = $(this).attr('data-hour-type:not("011")');
const hourID = $(this).attr('data-hour-type');
const Exclude = $(hourID).not("011");
What i am doing above doesn't seem to work since the first example returns me an undefined value and the second one returns me a list of k.fn.init values.
What can i do to exclude one or more values from a list using JQuery?
CodePudding user response:
jQuery has documentation. This should be your first stop when you have questions about specific jQuery functions and jQuery custom CSS operators.
.attr() retrieves the requested attribute from the first element in the collection. This isn't likely to be useful for what you're trying to do.
.not() returns a copy of the collection with the elements matching a selector removed. You might use it like this:
const hourID = $(this).not('[data-hour-type=011]');
:not() is an anti-selector. You might use it like this:
const hourID = $(this).filter(':not([data-hour-type=011])');
See also:
CodePudding user response:
The jQuery selector function always returns a collection of items. You can use the .filter() with a function argument to create a Boolean result; the .filter() throws away those items that do not return true.
jQuery(document).ready(function($) {
const notFiltered = $(".class-2")
const filtered = $(".class-2").filter((idx, el) => {
return !($(el).hasClass("class-1"))
})
// the filtered variable is used as the argument of
// $ (jQuery) function!
$(filtered).addClass("bg-red")
// setTimout is used so the .addClass() can be executed first
console.log('num of not filtered items:', notFiltered.length)
console.log('num of filtered items:', filtered.length)
})
.bg-red {
background-color: red;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >class-1 class-2</div>
<div >class-2 class-3</div>
<div >class-2 class-3</div>
