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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With