如何使用setAttribute在元素上设置多个类? [英] How can I use setAttribute to set multiple classes on an element?

查看:464
本文介绍了如何使用setAttribute在元素上设置多个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置一个元素有多个类?

How can I set an element to have multiple classes?

初始尝试:

element.setAttribute("class","class1","class2");
element.className="class1 , class2";
element.class="class1 , class2";


推荐答案

正常设置属性。它只是将属性设置为您传递的任何字符串,但不知道如何处理该值的任何特殊规则。

Just set the attribute as normal. It just sets the attribute to whatever string you pass it, it isn't aware of any special rules for how the value gets handled.

该属性需要一个空格分隔的列表的类别:

The attribute takes a space separated list of classes so:

element.setAttribute("class","class1 class2");

但是...旧版本(我认为7及更低版本)的Internet Explorer在他们的 setAttribute 实现 - 所以不要使用它。使用 className 属性。

However… older versions (I think 7 and lower) of Internet Explorer have serious bugs in their setAttribute implementation — so don't use it. Use the className property instead.

element.className = "class1 class2";

另请注意,这些是HTML类。他们使用超越风格的应用。没有CSS类的东西(虽然有类选择器,其他选择器,规则集和属性,所有这些都是(错误地和混淆的)在某个时候被称为类)。

Note, also, that these are HTML classes. They uses beyond the application of styles. There is no such thing as a CSS class (although there are class selectors, other selectors, rule sets and properties, all of which have been (incorrectly and confusingly) called "classes" at some time or another).

这篇关于如何使用setAttribute在元素上设置多个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆