gpt4 book ai didi

jquery - 如何将元素添加为文章元素的最后一个子元素

转载 作者:太空宇宙 更新时间:2023-11-03 19:42:00 25 4
gpt4 key购买 nike

<article>
<div><p></p></div>

<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<img/>
<p> i want to add element after this</p>


</article>

我有一个 article 元素,其中有许多元素是它的子元素,我想在 article 元素的结束标记之前添加最后一个元素。

我想要 jquery 中的一些代码在运行时随机执行此操作。

我的意图是在 article 元素之前添加 lastelemnt 只是示例,因为它可以是 div、ul 等

最佳答案

纯Javascript

您可以使用如下所示的纯 JavaScript 解决方案。这段代码:

  1. 获取 <article>通过使用 document.getElementById()
  2. 使用 .appendChild() 将新创建的元素添加到最后一个子元素的末尾(即文章的末尾)。

var article = document.getElementById("article");
var element = document.createElement("h1");
var text = document.createTextNode("Test");
element.appendChild(text);

article.appendChild(element);
#article {
background-color: red;
}
<article id="article">
<div>
<p></p>
</div>

<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<img/>
<p> i want to add element after this</p>


</article>

jQuery

此解决方案使用 jQuery。此代码使用 .append() 将元素添加到文章的末尾。就个人而言,我认为 jQuery 更简洁,但有时不是 best solution .

var article = document.getElementById("article");
var element = document.createElement("h1");
var text = document.createTextNode("Test");
element.appendChild(text);

$("#article").append(element);
#article {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article id="article">
<div>
<p></p>
</div>

<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<img/>
<p> i want to add element after this</p>


</article>

关于jquery - 如何将元素添加为文章元素的最后一个子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55410568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com