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

css - Change font size of ul element using javascript - Stack Overflow

programmeradmin3浏览0评论

Here is the css:

#content ul {
               font-size: 12px;
           }

I am trying this:

document.getElementById("content ul").style.fontSize = 8px;

But this is not working for me. Can anybody suggest how to do this?

Here is the css:

#content ul {
               font-size: 12px;
           }

I am trying this:

document.getElementById("content ul").style.fontSize = 8px;

But this is not working for me. Can anybody suggest how to do this?

Share Improve this question asked Feb 9, 2012 at 15:50 NoviceMeNoviceMe 3,26613 gold badges61 silver badges119 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

Two issues:

  1. Style properties are strings, so you need "8px" rather than 8px.

  2. getElementById gets elements by ID. You're passing in a pound selector (and you're missing the # from it). You'll have to use an ID and then find the children (via getElementsByTagName), or use querySelector (for the first matching element) or querySelectorAll (for all matching elements) instead. (Note that although well-supported in general, some older browsers don't have those last two; details.)

So for instance, here's how you would change the first matching element's font size on browsers with querySelector support:

document.querySelector("#content ul").style.fontSize = "8px";

Or all of them

var list = document.querySelectorAll("#content ul");
var index;
for (index = 0; index < list.length; ++index) {
    list[index].style.fontSize = "8px";
}

Or on older browsers:

var content = document.getElementById("content");
var list = content.getElementsByTagName("ul");
var index;
for (index = 0; index < list.length; ++index) {
    list[index].style.fontSize = "8px";
}

You need to select them properly. First you need to get the element that contains the <ul> in question.

var contentArea = document.getElementById("content");

Then you need to get the appropriate tags by tagname:

var tags = contentArea.getElementsByTagName("ul");

Then cycle through them to set the font size:

for (i=0; i<tags.length, i++)
{
    tags[i].style.fontSize = "8px"; // Don't forget the " here
}

<ul>'s are elements, not id's. Get the content element by id first. Then get child nodes inside that are unordered lists. Finally iterate over the list and change the size. And as TJ said, you need to pass in a string.

var lists = document.getElementById('content').getElementsByTagName('ul');
for (var i; i < lists.length; i++ ) {
     lists[i].style.fontSize = '8px';
}
发布评论

评论列表(0)

  1. 暂无评论