Reputation: 214969
Given some text and a html structure, how can I create a new html fragment where the structure is wrapped around the text?
Example:
text = "mytext"
html = "<div><p><span></span></p></div>"
Desired result:
newHtml = "<div><p><span>mytext</span></p></div>"
If possible, using pure jquery, without parsing html manually. Note that "text" is a literal string, not a text node in a document.
Of course, the code I'm looking for should work with arbitrary html, not just with the example above.
Upvotes: 2
Views: 135
Reputation: 20250
Credit to @Blender for this (posting as an answer as requested):
text = "mytext"
html = "<div><p><span></span></p></div>"
newHtml = $(html);
newHtml.find('*:last').text(text);
console.log(newHtml.get(0)); // <div><p><span>mytext</span></p></div>
So construct a jQuery object from the html
string, then find the :last
descendent (in this example, the span
), and set the text
.
Upvotes: 0
Reputation: 4288
You can achieve it with the help of place holder as follows,
text = "mytext"
oldHtml = "<div><p><span>[0]</span></p></div>"
newHtml = oldHtml.replace("[0]",text);
Upvotes: 0
Reputation: 440
Have you tried using .wrap() in jQuery? Try
$('span').wrap(text);
Upvotes: 0
Reputation: 2725
try following
var text = "mytext",
mainDiv = $("<div/>"),
para = $("<p/>"),
span = $("<span/>", {"html":text});
mainDiv.append(para.append(span));
//or you can write all above in one liner
i hope it helps.
Upvotes: 0
Reputation: 99234
Something along the lines of :
var text = "mytext";
var html = "<div><p><span></span></p></div>";
var div = $(html);
div.find('span').html(text);
div.appendTo(someOtherElement);
Upvotes: 2