Daniel Möller
Daniel Möller

Reputation: 86600

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.

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.

How can I do it? Answers without Jquery are ok as long as they're simple.

Upvotes: 2

Views: 166

Answers (3)

User863
User863

Reputation: 20039

Using contents() and 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>

Upvotes: 2

Victor
Victor

Reputation: 2909

Solution:

Use .nextSibling

Usage:

let text = $('.known')[0].nextSibling
$(text).after('<p>New Element</p>')

Demo:

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>

Upvotes: 1

Daniel M&#246;ller
Daniel M&#246;ller

Reputation: 86600

If the div before the text is known , you can select it, use .next() and then append before that:

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

Upvotes: 0

Related Questions