在 Javascript 中删除和克隆 DOM 元素 [英] Removing and cloning a DOM element in Javascript

查看:36
本文介绍了在 Javascript 中删除和克隆 DOM 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用其他人的 jquery 代码并尝试将功能添加到我自己的纯 JS 应用程序中.我遇到了一些我无法弄清楚的事情,它显然是获取一个 DOM 元素,将其删除,然后将其克隆以重新添加.jquery 以这个变量声明开头:

const template = $('#template').remove().removeAttr('id').removeAttr('style');

并且html中的元素看起来像这样...

当我在 jquery 中控制台记录元素时,它给了我一个像w.fn.init [p]"这样的对象,我猜这只是 jquery p 元素.我不确定为什么 'removeAttr' 被链接到初始删除,obvs 来打开和关闭显示,但不确定为什么如果您要删除元素,这很重要.template.parentNode.removeChild(template) 不会重新创建它.

模板变量然后在 jquery 中的一个函数中使用,就像这样......

const clone = template.clone();const input = clone.find('.p-input');

很明显,这是为了使用它而克隆元素.我试过了:

let clone = document.getElementById('template').cloneNode();

但这似乎只是克隆了没有内容的元素,所以当我尝试找到.p-input"时,我得到了空值.我将如何在普通 js 中重新创建它?

解决方案

我试过 let clone = document.getElementById('template').cloneNode(); 但这似乎只是克隆没有内容的元素...

没错.要克隆其内容,请将 true 传递到 cloneNode.

let template = document.getElementById('template');模板.remove();//或者在旧浏览器上:template.parentNode.removeChild(template);template.removeAttribute("id");template.removeAttribute("style");//...const clone = template.cloneNode(true);const input = clone.querySelector(".p-input");

但请记住,原始代码删除了元素,而这并没有.(我不清楚为什么它会删除它然后克隆它,但是...)

<小时>

你在评论中说你真的不明白为什么它会被删除,然后 id 和这样的东西被删除了.在由直接 DOM 操作驱动的页面中,这是一种相当常见的模式.页面的标记包括 #template 元素,然后在 DOM 加载代码中从页面中抓取 #template 元素,将其删除(因此它不再在页面中),并删除它用来在页面上找到它的 id.(style 的东西有点不寻常,但我猜测它以 style="display: none" 开头,所以它不会在页面加载期间显示.)然后,如有必要,它会克隆该元素并在页面上使用该克隆.

这里有一个简单的例子:

let template = document.getElementById('template');让列表 = template.parentNode;模板.remove();//或者在旧浏览器上:template.parentNode.removeChild(template);template.removeAttribute("id");template.removeAttribute("style");document.getElementById("btn-add").addEventListener("click", function() {const textField = document.getElementById("new-text");const valueField = document.getElementById("new-value");const text = textField.value;常量值 = valueField.value;如果(文本){const clone = template.cloneNode(true);clone.querySelector(".text").textContent = text;clone.querySelector(".value").value = value;list.appendChild(clone);textField.value = "";valueField.value = "";textField.focus();}});

添加条目:<div><label>Text:<input type="text" id="new-text"></label></div><div><label>值:<input type="text" id="new-value"></label></div><div><input type="button" id="btn-add" value="添加"></div>

<小时><div>列表:<ul><li id="template" style="display: none"><span class="text"></span><input class="value" type="text">

I'm taking someone else's jquery code and trying to add the functionality into my own application in plain JS. I've encountered something that I can't figure out, it's clearly taking a DOM element, removing it, and cloning it to add back in. The jquery starts with this variable declaration:

const template = $('#template').remove().removeAttr('id').removeAttr('style');

and the element in the html looks like this...

<p id="template" style="display: none;">

when I console log the element in the jquery it gives me an object like this 'w.fn.init [p]', which I'm guessing is just the jquery p element. I'm not sure why the 'removeAttr' are chained on to the initial remove, obvs to turn the display on and off but not sure why this is important if you're removing the element. template.parentNode.removeChild(template) doesn't recreate it.

The template variable is then used in a function in the jquery like this.....

const clone = template.clone();
const input = clone.find('.p-input');

which, obviously, is cloning the element in order to use it. I tried:

let clone = document.getElementById('template').cloneNode();

but that seems to just clone the element without the contents, so when I try and find the '.p-input' I get null. How would I recreate this in plain js?

解决方案

I tried let clone = document.getElementById('template').cloneNode(); but that seems to just clone the element without the contents...

Right. To clone its contents, you pass true into cloneNode.

let template = document.getElementById('template');
template.remove(); // Or on older browsers: template.parentNode.removeChild(template);
template.removeAttribute("id");
template.removeAttribute("style");
// ...
const clone = template.cloneNode(true);
const input = clone.querySelector(".p-input");

But remember that the original code removes the element, which this doesn't. (It's not clear to me why it removes it and then clones it, but...)


You said in a comment that you didn't really understand why it was being removed and then the id and such removed from it. It's a fairly common pattern in pages driven by direct DOM manipulation. The markup for the page includes the #template element, then on DOM load code grabs the #template element from the page, removes it (so it's not in page anymore), and removes the id it used to find it on the page. (The style thing is slightly unusual, but my guess is that it starts out with style="display: none" so it doesn't show during page load.) Then, as necessary, it clones that element and uses the clone on the page.

Here's a simple example of it at work:

let template = document.getElementById('template');
let list = template.parentNode;
template.remove(); // Or on older browsers: template.parentNode.removeChild(template);
template.removeAttribute("id");
template.removeAttribute("style");

document.getElementById("btn-add").addEventListener("click", function() {
    const textField = document.getElementById("new-text");
    const valueField = document.getElementById("new-value");
    const text   = textField.value;
    const value  = valueField.value;
    if (text) {
        const clone = template.cloneNode(true);
        clone.querySelector(".text").textContent = text;
        clone.querySelector(".value").value = value;
        list.appendChild(clone);
        textField.value = "";
        valueField.value = "";
        textField.focus();
    }
});

<div>
    Add an entry:
    <div><label>Text: <input type="text" id="new-text"></label></div>
    <div><label>Value: <input type="text" id="new-value"></label></div>
    <div><input type="button" id="btn-add" value="Add"></div>
</div>
<hr>
<div>
    The list:
    <ul>
        <li id="template" style="display: none">
            <span class="text"></span>
            <input class="value" type="text">
        </li>
    </ul>
</div>

这篇关于在 Javascript 中删除和克隆 DOM 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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