Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which one is given more preference for JavaScript or CSS?

here is my code

<!doctype html>
<html>
<head>
    <style>
        body {
            color:red;
        }
    </style>
    <script>
        window.onclick = function(){
            document.getElementsByTagName("body").color="blue";
        }
    </script>
</head>
<body>
    here is some text for test
</body>

when i run it in my browser (initially it is red) and click in window it doesn't respond to click i mean it should change the color of text from red to blue but nothing happens. Where am i wrong?

like image 595
chandola Avatar asked Feb 04 '26 08:02

chandola


2 Answers

Try this:-

Demo

This will add style attribute to the body element, which will override the css rule.

window.onclick = function(){
        document.getElementsByTagName("body")[0].style.color="blue";
    }

It should be style.color as color is a property of style property of element and even though it is body .getElementsByTagName returns a collection so you need to use document.getElementsByTagName("body")[0] to get the element and apply style to it.

And yes styles applied the element direclty will override the class css rule

like image 142
PSL Avatar answered Feb 06 '26 23:02

PSL


Style property has more precedence over styles applied by class.

document.getElementsByTagName("body").color="blue";

This has more preference

Also color is a property of style attribute.

So your style should have looked something like this as getElementsByTagName returns a node list.

document.getElementsByTagName("body")[0].style.color="blue";

it is a better idea to use classes instead, cause it is lot cleaner.

like image 38
Sushanth -- Avatar answered Feb 06 '26 23:02

Sushanth --



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!