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

Javascript - Applying class to an HTML tag given an attributevalue - Stack Overflow

programmeradmin1浏览0评论

I am trying to apply styles to HTML tags dynamically by reading in the value of certain HTML attributes and applying a class name based on their values. For instance, if I have:

<p height="30">

I want to apply a class="h30" to that paragraph so that I can style it in my style sheet. I can't find any information on getting the value of an attribute that is not an id or class. Help?

I am trying to apply styles to HTML tags dynamically by reading in the value of certain HTML attributes and applying a class name based on their values. For instance, if I have:

<p height="30">

I want to apply a class="h30" to that paragraph so that I can style it in my style sheet. I can't find any information on getting the value of an attribute that is not an id or class. Help?

Share Improve this question edited Jun 25, 2017 at 10:35 ɢʀᴜɴᴛ 32.9k15 gold badges121 silver badges114 bronze badges asked Sep 10, 2008 at 5:29 JoshuaJoshua 2151 gold badge4 silver badges9 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

I would highly remend using something like jquery where adding classes is trivial:

$("#someId").addClass("newClass");

so in your case:

$("p[height='30']").addClass("h30");

so this selects all paragraph tags where the height attribute is 30 and adds the class h30 to it.

See: getAttribute(). Parameter is the name of the attribute (case insensitive). Return value is the value of the attribute (a string).

Be sure to see the Remarks in MSDN before dealing with IE...

It's better to separate layout and presentation.

Despite using CSS, you're tying these two together. Use better class names (why does it have to have 30px height? Is it menubar? footer? banner?)

Attributes are just properties (usually). So just try:

for (e in ...) {
    if (e.height == 30) {
        e.className = "h30";
    }
}

Or use something like jquery to simplify this kind of stuff.

发布评论

评论列表(0)

  1. 暂无评论