So I'm trying to apply some css to every element on a page, but I don't want the css to apply to div's. I am currently using document.getElementsByTagName("*")
to select every element, but as far as I know there isn't anyway to filter out a certain element type. I think I found some code that does what I want but It was using jQuery and I don't want to use that in this project. Anyone know how to do this?
Asked
Active
Viewed 629 times
2

Michael Kremenetsky
- 59
- 1
- 1
- 8
-
Welcome to Stack Overflow! Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Jul 04 '21 at 06:42
2 Answers
4
You can use the below selector that will select all child element of body
which is not div
body *:not(div)
or
body :not(div)
const allExceptDiv = document.querySelectorAll("body *:not(div)");
allExceptDiv.forEach(el => el.classList.add("highlight"))
.highlight {
background: yellowgreen;
}
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<div>This is div</div>
<p> This is para </p>

DecPK
- 24,537
- 6
- 26
- 42
0
You can use the not selector
body :not(div) {
color: red;
}
<html><body>
<div>Hello</div>
<a>World</a>
</body></html>
Remember to include the body
, otherwise, body
will also be considered as an element that should have a color: red
style.
Reference:
https://developer.mozilla.org/en-US/docs/Web/CSS/:not

lengyue
- 1
- 1