如何使用常规 JavaScript 实现前置和附加?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3391576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:25:24  来源:igfitidea点击:

How can I implement prepend and append with regular JavaScript?

javascriptappendprepend

提问by Yosef

How can I implement prependand appendwith regular JavaScript without using jQuery?

如何在不使用 jQuery 的情况下使用常规 JavaScript实现前置附加

采纳答案by Grumdrig

Perhaps you're asking about the DOM methodsappendChildand insertBefore.

也许您在询问DOM 方法appendChildinsertBefore.

parentNode.insertBefore(newChild, refChild)

Inserts the node newChildas a child of parentNodebefore the existing child node refChild. (Returns newChild.)

If refChildis null, newChildis added at the end of the list of children. Equivalently, and more readably, use parentNode.appendChild(newChild).

在现有子节点之前插入节点newChild作为parentNode子节点refChild。(返回newChild。)

如果refChild为空,newChild则添加到子项列表的末尾。同样,更易读,使用 parentNode.appendChild(newChild).

回答by Pat

Here's a snippet to get you going:

这里有一个片段可以让你继续:

theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';

// append theKid to the end of theParent
theParent.appendChild(theKid);

// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);

theParent.firstChildwill give us a reference to the first element within theParentand put theKidbefore it.

theParent.firstChild将为我们提供对其中第一个元素的引用theParent并放在theKid它之前。

回答by Munzilla

You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element? If so here's how you can do it pretty easily:

您在这里没有给我们太多内容,但我认为您只是在问如何将内容添加到元素的开头或结尾?如果是这样,您可以通过以下方法轻松完成:

//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");

//append text
someDiv.innerHTML += "Add this text to the end";

//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;

Pretty easy.

挺容易。

回答by artur grzesiak

If you want to insert a raw HTML string no matter how complex, you can use: insertAdjacentHTML, with appropriate first argument:

如果你想插入一个原始的 HTML 字符串,无论多么复杂,你都可以使用: insertAdjacentHTML,带有适当的第一个参数:

'beforebegin'Before the element itself. 'afterbegin'Just inside the element, before its first child. 'beforeend'Just inside the element, after its last child. 'afterend'After the element itself.

'beforebegin'在元素本身之前。 'afterbegin'就在元素内部,在它的第一个子元素之前。 'beforeend'就在元素内部,在它的最后一个子元素之后。 'afterend'在元素本身之后。

Hint: you can always call Element.outerHTMLto get the HTML string representing the element to be inserted.

提示:您可以随时调用Element.outerHTML以获取表示要插入元素的 HTML 字符串。

An example of usage:

用法示例:

document.getElementById("foo").insertAdjacentHTML("beforeBegin",
          "<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");

DEMO

演示

Caution:insertAdjacentHTMLdoes not preserve listeners that where attached with .addEventLisntener.

注意:insertAdjacentHTML不保留附加有.addEventLisntener.

回答by moka

In order to simplify your life you can extend the HTMLElementobject. It might not work for older browsers, but definitely makes your life easier:

为了简化您的生活,您可以扩展HTMLElement对象。它可能不适用于较旧的浏览器,但绝对让您的生活更轻松:

HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;

HTMLElement.prototype.prepend = function(element) {
    if (this.firstChild) {
        return this.insertBefore(element, this.firstChild);
    } else {
        return this.appendChild(element);
    }
};

So next time you can do this:

所以下次你可以这样做:

document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);

回答by Raza

I added this on my project and it seems to work:

我在我的项目中添加了这个,它似乎有效:

HTMLElement.prototype.prependHtml = function (element) {
    const div = document.createElement('div');
    div.innerHTML = element;
    this.insertBefore(div, this.firstChild);
};

HTMLElement.prototype.appendHtml = function (element) {
    const div = document.createElement('div');
    div.innerHTML = element;
    while (div.children.length > 0) {
        this.appendChild(div.children[0]);
    }
};

Example:

例子:

document.body.prependHtml(`<a href="#">Hello World</a>`);
document.body.appendHtml(`<a href="#">Hello World</a>`);

回答by JamesH

Here's an example of using prepend to add a paragraph to the document.

下面是使用 prepend 向文档添加段落的示例。

var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);

result:

结果:

<p>Example text</p>

回答by akiespenc

In 2017I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:

在 2017 年,我知道 Edge 15 和 IE 12 的 prepend 方法不作为 Div 元素的属性包含在内,但如果有人需要快速参考 polyfill 函数,我做了这个:

 HTMLDivElement.prototype.prepend = (node, ele)=>{ 
               try { node.insertBefore(ele ,node.children[0]);} 
                     catch (e){ throw new Error(e.toString()) } }

Simple arrow function that's compatible with most modern browsers.

与大多数现代浏览器兼容的简单箭头功能。

回答by Steve Freed

You can also use unshift() to prepend to a list

您还可以使用 unshift() 附加到列表

回答by b3wii

var insertedElement = parentElement.insertBefore(newElement, referenceElement);

If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.

如果 referenceElement 为 null 或未定义,则将 newElement 插入到子节点列表的末尾。

insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.

Examples can be found here: Node.insertBefore

示例可以在这里找到:Node.insertBefore