tags:

views:

253

answers:

3

Hallo,

I would appreciate your advice. Given the following snippet:

<div id="parent"><div id="child">ChildText<span id="subchildtext"><b>SubChildText</b></span></div></div>

I want to:

  1. Extract the span Element
    ==>var span = $("#child").find("span");

  2. Prepend some Text ("foobar") and a new HTML element ("<b>foorbarbold</b>)
    ==>span.insertBefore("foobar<b>foobarbold</b>")

  3. Insert that new Element "into" the Parent (ID=PArent element)
    ==> $("#parent").html(span);

The result should be: <div id="parent">foobar<b>foobarbold</b><span id="subchildtext"><b>SubChildText</b></span></div>

But that doesnt work. I am not able to insert the new content to the extracted element. How could I accomplish this?

Thank you very much! Tim

A: 

I don't know jQuery, but here is how you do it with javascript

var span = document.getElementById("subchildtext");
var newBold = document.createElement("b");
newBold.appendChild(document.createTextNode("foobarbold"));
span.insertBefore(newBold, span.firstChild);
span.insertBefore(document.createTextNode("foobar"), span.firstChild)
Amarghosh
A: 

To set the html of the parent, try this:

$("#parent").html(span.html());

But you may find you need to remove the original, in which case you may need.

span.remove();

However, the following may work for you in one line (I've not tested it, but its on the right lines)

span.appendTo("#parent");

Or if you want it at the start

span.preprendTo("#parent");

Some links for you as well:

http://docs.jquery.com/Manipulation/prependTo

http://docs.jquery.com/Manipulation/remove

Hope this helps

James Wiseman
A: 

Try this:

$('#parent').html($('#subchildtext')).prepend('foobar<b>foodbarbold</b>');

Jimmy Cuadra