How Can You Place CSS in JavaScript?
This write-up will discuss examples of linking CSS with JavaScript.
How Can You Place CSS in JavaScript?
CSS can be placed in JavaScript by getting the HTML head element, creating a new link element, and setting its attributes for accessing the particular CSS file.
Check out the provided example to understand the stated concepts.
Example 1: Creating a Link in JavaScript and Appending it to the Heading Using CSS
In the following example, get the HTML head element using the “document.getElementsByTagName()” method which will include an element into the DOM (Document Object Model) dynamically:
Now, create a new link element using the “document.createElement()” method:
After that, set the attributes for the created link element for relating the current document with the linked document(CSS) by specifying the file type and the file name as follows:
linkCss.type= 'text/css';
linkCss.href= 'linkcss.css';
The “appendChild()” method will append the link element which is specified as its argument to the HTML head:
In the below step, access the created element named “link” using the class attribute:
Finally, apply the CSS styling on the added heading.
CSS Code
color: blue;
font-size: 24px;
text-align: center;
}
Output
In the above output, it can be observed that the CSS styling is applied on the specified heading by accessing the created link in JavaScript.
Example 2: Creating a Link in JavaScript and Appending it to div Using CSS
In the following example, repeat the above-discussed steps for getting the HTML head element, creating a new link element, assigning the attributes for the created link element, and appending the link element to the HTML head:
linkCss.rel= 'stylesheet';
linkCss.type= 'text/css';
linkCss.href= 'linkcss2.css'; document.getElementsByTagName('HEAD')[0].appendChild(linkCss);
Next, include a “div” in HTML and access the created link with the following value to be displayed on the DOM:
Lastly, implement the CSS styling on the specified div by referring to the created element “.link”. The styling includes the adjusting font-size, font-weight, color, background-color, padding, and text-align:
CSS Code
font-size: 24px;
font-weight: bold;
color: white;
background-color: green;
padding: 10px;
text-align: center;
}
Output
We have explained the procedure for placing CSS in JavaScript.
Conclusion
CSS can be placed in JavaScript by getting the HTML head, creating a new element, and setting the attributes for it, which results in linking the particular CSS file and appending it to the HTML head in order to be applied to the heading or div. This blog demonstrated the concept of placing CSS in JavaScript with the help of examples.
Source: linuxhint.com