Search code examples
javascriptapidomselectors-api

querySelectorAll with boundary conditions


document.querySelectorAll can be used to locate document elements with specific data attribute values. For instance

alert(document.querySelectorAll(".dk[data-kind='3']").length);
alert(document.querySelectorAll(".dk[data-kind>'3']").length);
<div class='dk' data-kind='2'>A</div>
<div class='dk' data-kind='3'>B</div>
<div class='dk' data-kind='4'>C</div>

However, from what I can tell it is not possible to define selectors that use inequalities such as data-kind>"3" - run the code snippet here and attempting querySelectorAllwith the boundary/inequality selector throws up an error.

jQuery provides mechanisms for doing such things albeit at the expense of a performance hit that is quite significant when dealing with mobile devices.

It would be a trivial matter to extract all data-kindelements and then testing their kind data for the boundary condition but I am wondering... - perhaps there is a way to write a clever query for querySelectorAll that I am not aware of?


Solution

  • You can use querySelectorAll to get all the elements having data-kind attribute. And filtering elements which satisfy certain condition.

    Array.from(document.querySelectorAll(".dk[data-kind]"))
    

    This statement will select all the elements having dk class and data-kind attribute. Array.from will convert the collection to Array so that array function can be directly used on it.

    .filter(el => Number(el.dataset.kind) > 3)
    

    This filter will filter the elements whose data-kind attribute value is greater than 3.

    var els = Array.from(document.querySelectorAll(".dk[data-kind]")).filter(el => Number(el.dataset.kind) > 3);
    console.log(els);
    console.log(els.length);
    <div class='dk' data-kind='2'>A</div>
    <div class='dk' data-kind='3'>B</div>
    <div class='dk' data-kind='4'>C</div>