JavaScript 中 class 和 classname 有什么区别?

What is the difference between class and classname in javascript?

为了找到某个 class 名称的子对象,我必须创建自己的辅助函数

findChildrenByTagName = function(obj, name){
    var ret = [];
    for (var k in obj.children){
        if (obj.children[k].className === name){
            ret.push(obj.children[k]);
        }
    }
    return ret;
}

它如何工作的一个例子是

var li = document.createElement('li');
var input = document.createElement('input');
input.setAttribute('class','answer_input');
li.appendChild(input);
console.log(findChildrenByTagName(li,"answer_input"));

然而,当我在上面的函数中用 class 替换上面的 className 时,代码不起作用。所以我很自然地想知道 class 和 className 之间有什么区别。快速搜索 google 不会显示任何内容。

此外,return 具有特定 class 名称的通用对象的子项列表的最佳方法是什么?如果不存在,有没有办法向所有对象添加一个方法,以便我可以调用

li.findChildrenByTagName("answer_input");

而不是上面的全局函数?

不要混淆 DOM 元素的保留字 'class' 和 'className' 属性。

根据MDN

The name className is used for this property instead of class because of conflicts with the "class" keyword in many languages which are used to manipulate the DOM.

编辑: 'class' word used on js 1.0 but in js 2.0 was merged with ECMAScript 4 相当不受欢迎和贬值。但它仍然是一个保留字。

让我们将其分解为可回答的部分:

问题 1:

What is the difference between class and classname in javascript?

你的标题问题。

答案 1:

Class 是 html 元素中的一个属性 <span class='classy'></span>

而另一方面,.className 是一个 属性,可以通过调用元素 get/set 其 class。

var element = document.createElement('span');
element.className = 'classy'
// element is <span class='classy'></span>

设置 class 也可以用 .getAttribute('class').setAttribute('class', 'classy') 完成。然而,我们经常更改操作 classes,因此它值得拥有自己的 .className 方法。


问题 2:

However when I replace className above by class in the function above, the code doesn't work. So I am naturally wondering what the difference is between class and className.

答案 2:element.class 不是 属性。

Class可能是一个元素的属性,但不能像el.class那样调用它。你的方法是 el.className就像你已经知道的那样。如果您查看 MDN for Element,您会发现元素有许多属性和方法,但 .class 不是一个。


问题 3:

Also what's the best way to return a list of children of a particular class name for a generic object?

答案 3:使用 .getElementsByClass名称

人们不是使用 purpose-made 函数,而是经常“链接”方法 one-after-another 来达到您想要的效果。

根据您的需要,我认为您要求的是 .getElementsByClassName 方法。以下是 full docs 和摘录:

The Element.getElementsByClassName() method returns returns a live HTMLCollection [array] containing all child elements which have all of the given class names.

要重复使用您回答中的示例:

var li = document.createElement('li');
var input = document.createElement('input');
input.setAttribute('class','answer_input');
li.appendChild(input);
console.log(li.getElementsByClassName("answer_input")[0]);
// would return the <input class='answer_input'> as the first element of the HTML array

一般概念是 class 是一个对象,class名称是其 properties.Refer 的 "one" 有关如何使用 class 的链接manipulation.Kindly 的属性如果我的 perception/understanding 错误,请纠正我。

https://www.w3schools.com/jsref/prop_html_classname.asp https://www.w3schools.com/jsref/prop_element_classlist.asp