了解基本的DOM链接

eze*_*zon 5 javascript dom

我开始使用JavaScript和DOM,试图故意远离jQuery等,至少在一段时间内.考虑到这一点,教程通常提供如下示例:

h = document.createElement("h1");
t = document.createTextNode("Hello.");
h.appendChild(t);
document.body.appendChild(h);
Run Code Online (Sandbox Code Playgroud)

为了简化这一点并避免变量,我成功地锁定了以下内容:

document.body.appendChild(document.createElement("h1")).appendChild(document.createTextNode("Hello."));
Run Code Online (Sandbox Code Playgroud)

虽然这有效,但我试图缩短以下前置操作:

h = document.createElement("h1");
t = document.createTextNode("Put this on top.");
h.appendChild(t);
document.body.insertBefore(h,document.body.firstChild);
Run Code Online (Sandbox Code Playgroud)

以下内容:

document.body.insertBefore(document.createElement("h1")).appendChild(document.createTextNode("Put this on top."),document.body.firstChild);
Run Code Online (Sandbox Code Playgroud)

但这次它没有按预期工作:文本放在BODY元素的最后,获得一个追加而不是前置.

我想成功的第一个案例只是一个侥幸,但我看不出这个链接练习有什么问题.

Ser*_*eyS 6

你在错误的地方有括号.你的路线:

document.body.insertBefore( document.createElement("h1") )
.appendChild( document.createTextNode("Put this on top."), document.body.firstChild );
Run Code Online (Sandbox Code Playgroud)

怎么样:

document.body.insertBefore(
    document.createElement("h1").appendChild(
        document.createTextNode("Put this on top.")), document.body.firstChild);
Run Code Online (Sandbox Code Playgroud)

现在你明白为什么在一行中合并所有这通常是一个坏主意.

好的,这个固定的行不会给你代码'带变量'的确切行为.这是因为.appendChild返回子DOM元素(<INPUT>在您的情况下),而不是父元素(在您的情况<H1>下).但是你想要<H1>在文档的开头添加所有DOM元素.要在一行中实现此目的,您需要使用.parentNode属性:

document.body.insertBefore(
    document.createElement("h1").appendChild(
        document.createTextNode("Put this on top.")).parentNode, document.body.firstChild)
Run Code Online (Sandbox Code Playgroud)

伙计们,请不要使用此类代码,这仅用于教育目的)))