I am looking for a way to add/change some properties in all tags of a certain type after the page is loaded.
I found two ways. But for some reason that I don't understand, the results are different.
Method 1 - adding a style tag as the last child of <html>.
var style = document.createElement( "style" );
style.innerHTML = `
div {
background-color: black;
color: white;
}
`;
document.documentElement.appendChild( style );
Result of style tag as last HTML child method
Method 2 - Getting all the tags of that type and painfully having it change them one.
var elems = document.body.getElementsByTagName("div");
for( let i = 0; i < elems.length; i ){
elems[i].style.backgroundColor = "black";
elems[i].style.color = "white";
}
So I was wondering why the results between the two methods are different, and I'm also happy to learn about other methods of changing all tags of a type of course.
CodePudding user response:
- the first method it creates a
<style>
tag and sets its attributes like you would write the css in the<style>
tag or enter it via<link>
- the 2nd method uses the
style
attribute of each tag which is also W3C standard but scoped to just that tag and has syntactic limitations (cannot use selectors like:hover
,:focus
...)
the 2nd method is faster than 1 and has higher precedence and no error about scoped
it is preferred in javascript
CodePudding user response:
Here, Method 1 adding a new style tag to the document and applying CSS styles using the innerHTML
. All tags on the page that match with the selector div
will have the styles using this technique. However, depending on how much styling is required, this technique may result in a slower page load.
Then,another method which is selecting the background and color properties of each div element on the page by looping through all of them. This approach is quicker because it doesn't need to wait for new styles to load.
So, another method you can use just by changing a bit in your second method is:
var elems = document.querySelectorAll("div");
for( let i = 0; i < elems.length; i ){
elems[i].style.backgroundColor = "black";
elems[i].style.color = "white";
}
Nevertheless, you can also use Jquery for shortcut execution :
$("div").css({
"background-color": "black",
"color": "white"
});
CodePudding user response:
The difference was priority. The same inline results of method 2 (loop/inline), were achieved with method 1 (<style>
as last child) by adding the !important
rule to increase the priority. Like so:
div {
background-color: black !important;
color: white !important;
}