Question

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.

Était-ce utile?

La solution 2

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

Autres conseils

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);

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.

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

    $('span').wrap(text);

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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top