Reputation: 3071
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?
Upvotes: 5
Views: 1546
Reputation: 115222
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>
Upvotes: 4
Reputation: 904
Use the function before
:
$("#mySpan").before("Raw text to insert. <span>Text inside span to insert. </span>")
EXAMPLE:
$("#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>
Upvotes: 3