While working on the front-end part of your project, CSS plays a major role in defining the styles for your web page.
With the help of knowledge in DOM (Document Object Model) and JavaScript, it is possible to change styles for your web page using script files. In this article, we will discuss the precedence of JavaScript with respect to CSS in terms of designing the website.
Example: Let’s consider an example index.html file, which will contain the HTML code for our webpage.
index.html
<!DOCTYPE html> < html lang = "en" dir = "ltr" > < head > < meta charset = "utf-8" > < title >Precedence example</ title > < link rel = "stylesheet" href = "styles.css" > </ head > < body > < h1 id = "mainh1" >This is an example heading</ h1 > < script src = "index.js" charset = "utf-8" ></ script > </ body > </ html > |
In the above, we have referenced two external files. Let’s go through them one by one.
CSS Code: The stylesheet link provided in the head section of the HTML code is referencing the “styles.css” file present in the current directory. Let’s define the CSS file as follows:
#mainh1 { color: red; }
The CSS file is targeting the elements which have id as “mainh1“. Clearly, if you see in the given example, our HTML file contains only one element that is an h1 heading, with this id. The CSS file intends to change the text color of the heading to red. If only CSS style is applied to the web page, then we will get the following output:
Output:
Now, let’s define the index.js file, which is referenced in the script tag just before the </body> tag. The JavaScript file is defined as
JavaScript Code:
index.js
document.getElementById( "mainh1" ).style.color = "blue" ; |
This JavaScript file first gets the element having id as “mainh1” and then uses style property to change the text color. Notice that the color is blue. When both of them are being used simultaneously, we get the following output.
Output:
This example clearly indicates that when both CSS and JavaScript target the same element, then the JavaScript changes are applied over CSS. Therefore, JavaScript has higher precedence than CSS.