skip to Main Content

How can i find all element that do not have a data- attribute without using jQuery, i have seen similar to my question but they are all using jQuery. check here

I need to exclude in my forEach the data-last attribute with the value of yes only.
Is there any method how to do that by using vanilla JS only? Thanks!

I’ve tried something like this but it is not working..

document.querySelectorAll(".form-step not:[data-last="yes"]")
<div class="form-step" data-last="no"> Stay </div>
<div class="form-step" data-last="no"> Stay </div>
<div class="form-step" data-last="yes"> Hide </div>

3

Answers


  1. If you can’t hardcode the data attribute to exclude – it isn’t possible with a single selector only. You’ll need to iterate over each element and filter out those with anything in the dataset.

    const formStepsWithutAnyData = [...document.querySelectorAll('.form-step')]
      .filter(div => Object.keys(div.dataset).length === 0);
    console.log(formStepsWithutAnyData.length);
    formStepsWithutAnyData[0].style.backgroundColor = 'yellow';
    <div class="form-step" data-last="no"> Stay </div>
    <div class="form-step" data-last="no"> Stay </div>
    <div class="form-step" data-last="yes"> Hide </div>
    <div class="form-step"> no data attribute </div>

    If you can hardcode the attribute to exclude, all you need is .form-step:not([data-last]) or the equivalent.

    Login or Signup to reply.
  2.   
    
    document.querySelectorAll('.form-step')
      .forEach(function(element) {
        if (!element.hasAttribute('data-last')) {
          console.log(element);
        }
      });
    <div class="form-step" data-last="no"> Stay </div>
    <div class="form-step" data-last="no"> Stay </div>
    <div class="form-step" data-last="yes"> Hide </div>
    <div class="form-step" > No Data attribute </div>
    Login or Signup to reply.
  3. Thank you for clarifying! Based on your need, you’re very close. The syntax for :not() is just slightly different. Here’s the tweaked code:

    document.querySelectorAll(‘.form-step:not([data-last="yes"])’)
    

    Besides the : and () changes, notice the lack of a space, since you need it to apply to that element and not a descendent. I also had to change one of the sets of quotes so they don’t mess with each other, but I don’t believe it matters which is changed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search