'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.
Solution 1:[1]
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>
Solution 2:[2]
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");
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |
