I am developing a game that glitches at some point through using the CSS filter: invert(1);
property. However, when you use that property on body
, it makes everything position: absolute;
. This is not good because I need most elements to be fixed
, and everything goes to a negative top
and not visible. How can I effectively get all elements in a list that isn't a parent to any other elements, but included if it has text? Any answers or other stack overflow topics would be nice: Here is some of my code:
// In a working loop called Repeat()
if(Glitch == 1) {
document.querySelector(".ChangableStyles").innerHTML = "* {filter: invert(1)}"
} else {
document.querySelector(".ChangableStyles").innerHTML = ""
}
Edit: Since all of you are asking, the .ChangableStyles
tag is a style element. The filter on everything applies when I change the innerHTML
of that style tag to valid CSS styles. I don't want to be rude, but I have the .ChangableStyles
thing figured out. Thank you.
You mention you already have a list of elements, but it's not clear how you're generating that list. I've gone ahead on the assumption you're wanting to "select" all elements in <body></body>
that don't have any children.
You can use a combination of Array.from()
, your pre-existing selection logic, and a filter()
using node.childElementCount === 0
to accomplish what you describe. However on higher-complexity DOMs this will be computationally expensive, so I would implore you to re-consider your design instead of opting for this route. To be clear, this will meet your requirement of selecting ANY Node
in the DOM which has no child elements ("isn't a parent to any other elements"), which includes any script
, style
or other "user-invisible" nodes in the body
.
document.getElementById('get-elements-button').addEventListener('click', function () { console.log(Array.from(document.body.getElementsByTagName("*")).filter(function (node) { return node.childElementCount === 0; })); });
<div class="has-child-elements"> <a href="#">This is a child element</a> </div> <div class="has-no-child-elements"> </div> <div class="has-child-elements"> <a href="#">This is also a child element</a> </div> <button id='get-elements-button'>Get elements with child elements →</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.