Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - insertBefore() for raw text

I use jQuery 1.11.2 and jQuery-migrate 1.2.1. Here is the simple example of what I'm trying to do:

https://jsfiddle.net/bek3wrug/

I want to insert some text (not fully-wrapped into HTML tag) before some element on page, and jQuery only inserts the part that is wrapped inside HTML tag. I cannot use prepend() as I don't want to insert it inside some element, I need to insert it before.

Is there a way to make jQuery insert all the text, not only wrapped into HTML tags?

like image 935
coolguy Avatar asked Feb 13 '17 09:02

coolguy


1 Answers

Since it contains textNode you need to use jQuery.parseHTML method, which generates an array of nodes. Otherways it will be interpreted as a selector and nothing would happen since nothing get selected using the string.

$($.parseHTML("Raw text to insert. <span>Text inside span to insert. </span>")).insertBefore("#mySpan")

Refer: Creating new elements using jQuery.

$($.parseHTML("Raw text to insert. <span>Text inside span to insert. </span>")).insertBefore("#mySpan")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
  <span id="mySpan">Original text</span>
</div>

Or use before() method.

$("#mySpan").before("Raw text to insert. <span>Text inside span to insert. </span>")

$("#mySpan").before("Raw text to insert. <span>Text inside span to insert. </span>")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
  <span id="mySpan">Original text</span>
</div>
like image 55
Pranav C Balan Avatar answered Oct 05 '22 23:10

Pranav C Balan