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?
- Welcome to Stack Overflow! Please visit help center, take tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output, preferably in a Stacksnippetmplungjan– mplungjan2021-07-04 06:42:49 +00:00Commented Jul 4, 2021 at 6:42
Add a comment |
2 Answers
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> Comments
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