简体   繁体   中英

How to override CSS with javascript?

i found custome code css like this

 header.type-2:not(.fixed-header) nav>ul>li>a{ color:#000; } 

i'm trying override the color to #fff with javascript, but still no luck.

with this code below :

 <script> var elems = document.getElementsByClassName('header.type-2:not(.fixed-header) nav>ul>li>a'); for(var i = 0; i < elems.length; i++) { elems[i].style.color = '#fff'; } </script> 

i cannot direct edit in css style, because i don't have permission for, but the interest is, i can execute simple javascript syntax like alert();

Please help me.

document.getElementsByClassName selects elements by their class , it does not work with a complex selector as in your example.

You can use document.querySelectorAll instead.

var elems = document.querySelectorAll('header.type-2:not(.fixed-header) nav>ul>li>a');

You are not querying by class but by selector, use querySelectorAll

 var elems = document.querySelectorAll('header.type-2:not(.fixed-header) nav>ul>li>a'); //console.log(elems) for(var i = 0; i < elems.length; i++) { elems[i].style.color = '#f00'; } 
 header.type-2:not(.fixed-header) nav>ul>li>a{ color:#000; } 
 <header class="type-2"> <nav><ul><li><a href="#">BOB</a></li></ul></nav> </header> 

This beautyfull oneliner might do the trick. You just need to specify the function for it. What do you suppose should trick the event to change to CSS ?

What it does is that it change the width from its previous value to the value written below. It could also be a variable. The ClassToLookFor is the class it will change the value on.

In below case I change the width of a class IF a specified class (here it is tricker ) is present on the page (I use it for a more responsive webpage).

$(function(){
if (!$(".tricker").length) $(".ClassToLookFor").css('width', '100%');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM