如何将类添加到由appendChild创建的元素 [英] How to add class to an element create by appendChild

查看:473
本文介绍了如何将类添加到由appendChild创建的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下如何在javascript中为appendChild创建的元素添加一个类

I want to ask how to add a class for an element I create by appendChild in javascript

document.forms[0].appendChild(document.createElement("input"));

如何为我创建的输入元素添加一个类?

How to add a class for the input element I created?

我只是使用Javascript,我不喜欢jQuery,请用纯javascript发送答案。

I just use Javascript and I don't like jQuery, please send answer in pure javascript.

推荐答案


我想问一下如何在javascript中为appendChild创建的元素添加一个类

I want to ask how to add a class for an element I create by appendChild in javascript

像任何其他元素你有参考。如果它是通过 createElement 在JS中创建的,则无关紧要,或者您以其他方式获得对该节点的引用。假设输入包含对节点的引用:

Like any other element you have a reference. It doesn't matter if it's created in JS via createElement, or you obtained a reference to the node in another way. Assuming input contains the reference to your node:

var input = document.createElement("input");

您可以使用 className

input.className = "foo";

classList

input.classList.add("foo");

setAttribute

input.setAttribute("class", "foo");

第一个被任何浏览器广泛支持,所以我强烈建议除非你不是在现代浏览器中,您想要操作您设置的每个类,因此 classList 将更有用。我强烈避免使用后者,因为使用 setAttribute 你将设置HTML的属性而不是JS对象的类名:然后浏览器将该值映射到JS的属性但在某些情况下它会失败(例如,参见某些版本的IE),因此即使HTML节点具有该属性,也不会应用该类。

The first one is widely supported by any browser, so I strongly suggest that one unless you're not in a modern browser and you want to manipulate each class you set, so classList will be more useful. I strongly avoid the latter, because with setAttribute you're going to set the HTML's attribute not the class name of the JS object: then the browser will map that value to the JS's property but in some cases it will fails (see, for instance, some versions of IE) so the class won't be applied even if the HTML node will have that attribute.

请注意,尽管如何获得 HTML 节点参考,但上述所有方法仍然有效,因此还包括:

Notice that all the methods above are working despite how to HTML node reference is obtained, so also with:

var input = document.getElementById("my-input");

等等。

在你的case,因为 appendChild 返回对附加节点的引用,你也可以在一个语句中写下每一个:

In your case, because appendChild returns the reference to the node appended, you can also write everyting in one statement:

document.forms[0]
    .appendChild(document.createElement("input"))
    .className = "foo";

希望有所帮助。

这篇关于如何将类添加到由appendChild创建的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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