Register now or log in to join your professional community.
We can add CSS to javascript by three ways.
1. External CSS file
<head><link rel="stylesheet" type="text/css" href="mystyle.css"></head>
2. Internal CSS file
<style>body { background-color: linen;}h1 { color: maroon; margin-left: 40px;} </style>
3.Inline Styles
<h2 style="color:blue;margin-left:30px;">This is a heading</h1>
we have add css to javscript in 3 ways.
1) External Css File
2) Internal Css File
3) Inline Css File
if you want to add css text :
//Create New Element <style></style>
var style = document.createElement('style');
// Add Tag Attribute
style.type = 'text/css';
//Write You CSS Code
style.contentText = ' /* ...Your CSS Code ...*/';
//Insert the style element in the head element
document.getElementByTagName('head')[0].appendChild(style);
If You Want To add externe CSS File :
//Create New Element <link />
var link = document.createElemnt('link');
// Add Link Attributes
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('rel', 'YourCssUrlPath');
//Insert the style element in the head element
document.getElementByTagName('head')[0].appendChild(style);
If you want specific element
//Get the element form the document (s) , get By TagName/ ID/ ClassName ...
var element = ..... /* choose the best foe you */
// set the CSS Property
element.style.popertyName = Value ;
where
popertyName => CSS property name (e.g: color/ backgroundColor / ....)
(int | string ) value => CSS Property Value (e.g: 100/ ' red' / '200px'....)
first i select the element from the page then
element.style.property = value
or i can create a new classes style in css and adding them to elements by classlist property in javascript
I can add CSS in three ways i.e
Internal Css
External Css
Inline
I Prefer to use External css because code understanding is good if we make separate css file rather than creating in same file where scripts are written.
<script> document.getElementById("divid").style.color = "blue";</script>
the first way to load a style sheet using java script is
$('head').append('<link rel="stylesheet" type="text/css" href="style.css">');the second way to load a style sheet using java script is
var element = document.createElement("link"); element.setAttribute("rel", "stylesheet"); element.setAttribute("type", "text/css"); element.setAttribute("href", "external.css"); document.getElementsByTagName("head")[0].appendChild(element);
we should write the path of CCS file
By using below mentioned code in javaScript we can add css to page:-var style1=document.createElement('style') style1.innerHTML = "div {border: 2px solid black; background-color: blue;}"; document.body.appendChild(style1);
document.getElementById(id).style.property = new style
We can add CSS to javaScript in 3 ways.
1. Inline CSS.
2. Internal CSS.
3. External CSS.