Home > Software design >  Change style of tag from javascript
Change style of tag from javascript

Time:04-27

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.

CodePudding user response:

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>

CodePudding user response:

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");

CodePudding user response:

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

  • Related