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 ?
- can you show also your html part – S. S. Rawat Commented Aug 30, 2013 at 4:30
4 Answers
Reset to default 2Using 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');
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745594046a4635000.html
评论列表(0条)