简体   繁体   中英

Use the CSS Universal Selector '*' with javascript?

I've been asked to write a sample script that will make use of the CSS's universal selector. How do I do it? I know that this is the universal selector in CSS :

 * { //Universal Selector '*' to set/reset property values
    margin: 0;
    padding: 0;
}

Sample code:

<!DOCTYPE html>
<html>
<body>

<h2 class="example" style="padding:50px;" >A heading with class="example"</h2>
<p>Click the button to activate the universal selector.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
    document.body.style.margin = 0;
    document.body.style.padding = 0;
}
</script>

</body>
</html>

On click, the button should reset all margins and paddings of elements to 0. But instead, it does it for the body only.

Clarification: Specifically, I need a javascript method that sets all margins and paddings for all elements to 0.

只需使用jQuery的$('*')document.querySelectorAll("*")

Here is a simple sample to start with and it iterates through the body's elements.

 <!DOCTYPE html> <html> <body> <h2 class="example" style="padding:50px;" >A heading with class="example"</h2> <p>Click the button to activate the universal selector.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var els = document.body.querySelectorAll("*"); for (var i = 0; i < els.length; i++) { els[i].style.margin = 0; els[i].style.padding = 0; } } </script> </body> </html> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM