简体   繁体   中英

Change style of tag from javascript

I would like to know if we can change the css of a tag in html from javascript. i know a approach of getting all elements with that tag using document.getElementsbyTagName and using a for loop to change the css properties of each... however im looking for an approach which might be much more compact like this document.getElementsbyTagName("p").style.color = "red"
EDIT: using.forEach is almost the same as using a for loop.... I didnt want to use this approach as it will take time to process all of the elements especially when the pages scale to have lots of p tags.

This is a one liner, less than this is impossible.

document.querySelectorAll("p").forEach(p => p.style.color = "red")

 document.querySelectorAll("p").forEach(p => p.style.color = "red")
 <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p>

You could make a helper function that does it for you, maybe something like this:

function doAll(tagName, action) {
    document.querySelectorAll(tagName).forEach(action);
}
doAll("p", element => element.style.color = "red");

I'm not sure if changing style of tags without loop is possible. Though you can change style of a class or tag by changing properties of a stylesheet using javascript.

Reference: Change CSS of class in Javascript? MDN Docs Reference:StyleSheetList

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