steady_progress steady_progress - 14 days ago 6
HTML Question

Selecting elements based on absence of class-attribute in HTML DOM

Using the HTML DOM, I would like to select almost all td tags except for those td tags that have a class-attribute of "xyz".

With document.selectElementsByTagname["td"] I can get all the td-elements. However, I don't want all but only those where the class-attribute != "xyz".

Since there are no predicates in html DOM, I currently don't see a way to achieve this. Is there still a way to do it?

Answer

You can use querySelectorAll with :not() pseudo class selector.

document.querySelectorAll("td:not(.xyz)")

Array.from(document.querySelectorAll("td:not(.xyz)")).forEach(function(e) {
  e.style.color = "red";
})
<table>
  <tr>
    <td class="xyz">a</td>
    <td class="xyz">a</td>
    <td>a</td>
    <td class="xyz">a</td>
    <td>a</td>
    <td class="xyz">a</td>
  </tr>
</table>

Comments