最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Change css style of a subclass with javaScript - Stack Overflow

programmeradmin1浏览0评论

How can a css style subclass can be changed with javaScript ?

To make myself clear let's say 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 margin of the ul#main-menu using the code: document.getElementById('main-menu').style.marginLeft='10px';

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

How can a css style subclass can be changed with javaScript ?

To make myself clear let's say 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 margin of the ul#main-menu using the code: document.getElementById('main-menu').style.marginLeft='10px';

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

Share Improve this question asked Aug 30, 2013 at 4:19 Suciu LucianSuciu Lucian 4304 silver badges12 bronze badges 1
  • can you show also your html part – S. S. Rawat Commented Aug 30, 2013 at 4:30
Add a ment  | 

4 Answers 4

Reset to default 2

Using the Selectors API

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

Without using jQuery, this snippet will store each a it can find in each li in your main menu. Then, it will go through each item and set its 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're using jQuery, you can acplish the same thing like so:

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

However, be aware that it is not good practice to set style rules with 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 that therefore behave like you wish.

document.getElementById('main-menu').getElements("li a").style.color="some_color";
// Or simply
document.getElements("#main-menu li a").style.color="some_color";
$('#main-menu li a').css('color':'Red');
发布评论

评论列表(0)

  1. 暂无评论