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

发布于 2024-09-12 17:08:42 字数 176 浏览 10 评论 0原文

如何实现 prepend附加 与常规 JavaScript 而不使用 jQuery?

How can I implement prepend and append with regular JavaScript without using jQuery?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

神经大条 2024-09-19 17:08:43

下面是一个可以帮助您入门的代码片段:

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.firstChild 将为我们提供对 theParent 中第一个元素的引用,并将 theKid 放在它前面。

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.firstChild will give us a reference to the first element within theParent and put theKid before it.

最美的太阳 2024-09-19 17:08:43

也许您正在询问 DOM 方法 appendChildinsertBefore

parentNode.insertBefore(newChild, refChild)

将节点 newChild 作为 parentNode 的子节点插入到
现有子节点refChild。 (返回newChild。)

如果refChild为空,则将newChild添加到列表的末尾
孩子们。等效地,并且更具可读性,使用
parentNode.appendChild(newChild)

Perhaps you're asking about the DOM methods appendChild and insertBefore.

parentNode.insertBefore(newChild, refChild)

Inserts the node newChild as a child of parentNode before the
existing child node refChild. (Returns newChild.)

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

绿光 2024-09-19 17:08:43

您在这里没有给我们太多内容,但我认为您只是问如何将内容添加到元素的开头或结尾?
如果是这样,您可以轻松地做到这一点:

//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;

非常简单。

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.

就此别过 2024-09-19 17:08:43

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

'开始之前'
在元素本身之前。
'开始后'
就在元素内部,在它的第一个子元素之前。
'之前'
就在元素内部,在其最后一个子元素之后。
'尾声'
在元素本身之后。

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

使用示例:

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

DEMO

警告: insertAdjacentHTML 不保留使用 .addEventLisntener 附加的侦听器。

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

'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.

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

An example of usage:

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

DEMO

Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.

无远思近则忧 2024-09-19 17:08:43

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

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]);
    }
};

示例:

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

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>`);
真心难拥有 2024-09-19 17:08:43

为了简化您的生活,您可以扩展 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);
    }
};

所以下次您可以这样做:

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

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

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);
ㄖ落Θ余辉 2024-09-19 17:08:43

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

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

结果:

<p>Example text</p>

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

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

result:

<p>Example text</p>
忆悲凉 2024-09-19 17:08:43

在 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()) } }

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

In 2017 I 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:

 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.

给我一枪 2024-09-19 17:08:43
var insertedElement = parentElement.insertBefore(newElement, referenceElement);

如果 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.

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

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

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

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

笑红尘 2024-09-19 17:08:43

您还可以使用 unshift() 添加到列表前面

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

才能让你更想念 2024-09-19 17:08:43

document.write() 不是一个好的做法,如果您使用它,某些浏览器(例如 Chrome)会向您发出警告,如果您将其提供给客户,那么这可能是一个糟糕的解决方案,他们不想使用您的代码并且在调试控制台中查看警告!

另外,如果您将代码提供给已经在其网站上使用 jQuery 实现其他功能的客户,那么 jQuery 也可能是一件坏事,如果已经有不同版本的 jQuery 正在运行,就会出现冲突。

如果你想将内容插入到 iframe 中,并使用纯 JS 来实现,没有 JQuery,也没有 document.write(),我有一个解决方案。

您可以使用以下步骤

1.选择您的 iframe:

var iframe = document.getElementById("adblock_iframe");

2.创建一个要插入到框架中的元素,比如说图像:

var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
    img.style.width = "200px";
    img.style.height = "50px";
} else {
    img.style.width = "400px";
    img.style.height = "100px";
}
img.id = "image";

3.将图像元素插入到 iframe 中:

iframe.contentWindow.document.body.appendChild(img);

document.write() is not a good practice, some browsers like Chrome give you a warning if you use it, and it may be a bad solution if you are providing it to a customer, they don't want to use your code and see warnings in the debug console!

Also jQuery may also be a bad thing if you are giving your code to a customer who already uses jQuery for other functionality on their site, there will be a conflict if there is already a different version of jQuery running.

If you want to insert content into an iframe, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution.

You can use the following steps

1.Select your iframe:

var iframe = document.getElementById("adblock_iframe");

2.Create an element that you want to insert into the frame, let's say an image:

var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
    img.style.width = "200px";
    img.style.height = "50px";
} else {
    img.style.width = "400px";
    img.style.height = "100px";
}
img.id = "image";

3.Insert the image element into the iframe:

iframe.contentWindow.document.body.appendChild(img);
女皇必胜 2024-09-19 17:08:43

我们终于有了一个所有现代浏览器都支持的内置 prepend() 方法

parent.prepend(newChild)

https ://caniuse.com/dom-manip-convenience

We finally have a built-in prepend() method supported by all modern browsers

parent.prepend(newChild)

https://caniuse.com/dom-manip-convenience

无妨# 2024-09-19 17:08:43

这不是最好的方法,但如果有人想在所有内容之前插入一个元素,这里有一个方法。

var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

This is not best way to do it but if anyone wants to insert an element before everything, here is a way.

var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文