John Wick
John Wick

Reputation: 509

querySelector error: Not valid selector

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

Answers (2)

dloeda
dloeda

Reputation: 1548

There are multiple issues this code:

  1. You cannot use " inside .not the selector
  2. As @AndrewBone said, probably you want to use querySelectorAll
  3. 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

John Wick
John Wick

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

Related Questions