[英]Jquery - append element after an element's text with multiple elements inside
This is not a duplicate of jQuery - add element after text , because the element where I want to insert has more elements besides the text, using append places my element in the wrong place.这不是jQuery - add element after text的副本,因为我要插入的元素除了文本之外还有更多元素,使用 append 将我的元素放在错误的位置。
Suppose I have many elements like:假设我有很多元素,例如:
<li class="target-line">
<blablabla></blablabla>
<div class="known">...</div>
Element's text
<...variable element, can't query it to use .before()></...>
<more elements/>
</li>
And I want to insert a complex element newElement
(not one that I can just write as a string) right after the Element's text
.我想在
Element's text
之后插入一个复杂的元素newElement
(不是一个我可以写成字符串的Element's text
。
How can I do it?我该怎么做? Answers without Jquery are ok as long as they're simple.
没有 Jquery 的答案是可以的,只要它们很简单。
Using contents()
and filter()
使用
contents()
和filter()
$('.target-line').contents().filter(function() { return this.nodeType === 3 && this.textContent.includes("Element's text") // if text is known }).after('<div>New Element</div>')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <li class="target-line"> <blablabla></blablabla> <div class="known">...</div> Element's text <div class="unknown">...</div> <div class="unknown2">...</div> </li>
Use .nextSibling
使用
.nextSibling
let text = $('.known')[0].nextSibling
$(text).after('<p>New Element</p>')
let text = $('.known')[0].nextSibling $(text).after('<p>New Element</p>')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <li class="target-line"> <blablabla></blablabla> <div class="known">...</div> Element's text <div class="unknown">...</div> <div class="unknown2">...</div> </li>
If the div before the text is known , you can select it, use .next()
and then append before that:如果文本之前的 div 是已知的,您可以选择它,使用
.next()
然后在其之前追加:
$rows = $("li.target-line div.known") // get the known div
$afterText = $rows.next() //get the first element after the div
$afterText.before(newElement); //insert your element before that
Didn't check what could happen if there were no elements after the text.没有检查如果文本后面没有元素会发生什么。 In this case there is always at least one.
在这种情况下,总是至少有一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.