Home > Software engineering >  Add styling only to elements with a child
Add styling only to elements with a child

Time:01-06

I have multiple <p> with the same class names, and only one has a child. I'm trying to only highlight the <p> that has a child, but my code highlights all of them.

window.onload = function() {
  var highlight = document.getElementsByClassName('parent');

  for (let i = 0; i < highlight.length; i  ) {
    if (document.querySelectorAll(".parent .child").length > 0) {
      highlight[i].style.backgroundColor = "yellow";
    }
  }
}
<p >
  Testing 1
</p>
<p >
  Testing 2
  <span >
    test
  </span>
</p>
<p >
  Test 3
</p>
<p >
  Testing 4
</p>

CodePudding user response:

In recent browsers, you can do this with a single selector string - select .parents which have a child with :has(> .child).

for (const p of document.querySelectorAll('.parent:has(> .child)')) {
  p.style.backgroundColor = "yellow";
}
<p >
  Testing 1
</p>
<p >
  Testing 2
  <span >
    test
  </span>
</p>
<p >
  Test 3
</p>
<p >
  Testing 4
</p>

Otherwise, going with your curent code, you'll have to reference the element being iterated over (the highlight[i]), and call querySelector on it to see if that one element has any matching children.

window.onload = function() {
  var highlight = document.getElementsByClassName('parent');

  for (let i = 0; i < highlight.length; i  ) {
    if (highlight[i].querySelector(".parent .child")) {
      highlight[i].style.backgroundColor = "yellow";
    }
  }
}
<p >
  Testing 1
</p>
<p >
  Testing 2
  <span >
    test
  </span>
</p>
<p >
  Test 3
</p>
<p >
  Testing 4
</p>

CodePudding user response:

I wouldn't use javascript for this just use the has selector

p:has(span) {
    background-color:#f00!important
}
  • Related