2

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.

georg
  • 211,518
  • 52
  • 313
  • 390

5 Answers5

2

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);
OneOfOne
  • 95,033
  • 20
  • 184
  • 185
  • Thanks, but this only works with my specific example. I'm looking for a more general approach. – georg Aug 09 '13 at 11:53
  • I think you're looking into templates, check http://stackoverflow.com/questions/14062368/new-recommended-jquery-templates – OneOfOne Aug 09 '13 at 12:04
0

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.

maverickosama92
  • 2,685
  • 2
  • 21
  • 35
0

Have you tried using .wrap() in jQuery? Try

    $('span').wrap(text);
melvindidit
  • 430
  • 2
  • 6
  • 15
0

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);
Jatin patil
  • 4,252
  • 1
  • 18
  • 27
0

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.

Here's a fiddle

Community
  • 1
  • 1
billyonecan
  • 20,090
  • 8
  • 42
  • 64