Reputation: 509
I am finding the max number of an element based on data attributes, however I want to convert jquery code to native vanilla js. I have tried to replace $ selector with querySelector of vanillaJS, but it throws an error like this. Is there a way I can convert this to vanilla JS. This is the error it returns.
DOMException: Failed to execute 'querySelector' on 'Document': 'li:not(".expired")[data-arrange]' is not a valid selector
This is my code.
var max = Math.max.apply([], document.querySelector('li:not(".expired")[data-arrange]').map(function() {
return $(this).data('arrange');
}).get());
sample HTML
<ul>
<li data-arrange="1" class="rec expired">bONIE</li>
<li data-arrange-"4" class="rec">eDS</li>
<li data-arrange="5" class="expired">bue</li>
<li data-arrange="6" class="rec">mag</li>
</ul>
Thank you.
Upvotes: 0
Views: 9954
Reputation: 1548
There are multiple issues this code:
"
inside .not
the selectorquerySelectorAll
querySelectorAll
returns a NodeList[]
so .map
will break the execution.So I guess the correct code must be:
var selector = 'li:not(.expired)[data-arrange]';
var array = Array.prototype.slice.call(document.querySelectorAll(selector));
var max = Math.max.apply(null, array.map(function(item) {
return parseInt(item.dataset.arrange);
}));
console.info(max)
<ul>
<li data-arrange="1">1</li>
<li data-arrange="4">4</li>
<li data-arrange="5">5</li>
<li data-arrange="6">6</li>
</ul>
Upvotes: 2
Reputation: 509
I have solved it using dloeda's code. I've just modified it a liitle bit, because it returns an error using .get();
var selector = 'li:not(.expired)[data-arrange]';
var array = Array.prototype.slice.call(document.querySelectorAll(selector));
var max = Math.max.apply(Math, array.map(function(item) {
return item.dataset.arrange;
}));
Upvotes: 0