Changing css style subclass using javaScript

How can a subclass of CSS style be changed using javaScript?

To make sure we have the following code:

ul#main-menu{ margin:0 0 0 285px; padding:0 0 0 0; list-style:none; } ul#main-menu li a{ margin:0 0 0 0; padding:8px 10px 7px 10px; color:#FFF; } 

I can change the edge of the ul # main menu using the code: document.getElementById('main-menu').style.marginLeft='10px';

So how can I change the color of li a using javaScript?

+4
source share
4 answers

Using the API Selector

 var anchors = document.querySelectorAll('ul#main-menu li a'); for(var i = 0, len = anchors.length; i < len; i ++) { anchors[i].style.color = 'red'; } 

Using plain old JavaScript:

 var lis = document.getElementById('main-menu').children; Array.prototype.forEach.call(lis, function(li) { var anchors = li.getElementsByTagName('a'); Array.prototype.forEach.call(anchors, function(a) { a.style.color = 'green'; }); }); 

jsFiddle Demo

+2
source

Without jQuery, this snippet will save every a that it can find in every li in the main menu. Then it will go through each element and set the text color to red .

 var a_list = document.querySelectorAll('#main-menu li a'); for (var i=0; i<a_list.length; i++) { a_list[i].style.color = 'red'; } 

If you use jQuery, you can do the same thing:

 $('#main-menu li a').css('color','red'); 

However, keep in mind that it is not recommended to set style rules using JavaScript, as this is what CSS was designed for. It would be much better if you used JavaScript to add a class (perhaps something like .higlighted-text ) to your a elements, which therefore behave as you wish.

+1
source
 document.getElementById('main-menu').getElements("li a").style.color="some_color"; // Or simply document.getElements("#main-menu li a").style.color="some_color"; 
0
source
 $('#main-menu li a').css('color':'Red'); 
0
source

Source: https://habr.com/ru/post/1499731/


All Articles