2

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.

Daniel Möller
  • 84,878
  • 18
  • 192
  • 214

3 Answers3

2

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>
User863
  • 19,346
  • 2
  • 17
  • 41
1

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>
Community
  • 1
  • 1
Victor
  • 2,864
  • 1
  • 12
  • 20
0

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.

Daniel Möller
  • 84,878
  • 18
  • 192
  • 214