2

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?

1

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.