JQuery: How to Extract Element and insert Text/Element before the extracted Element?
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:
Extract the span Element
==>var span = $("#child").find("span");
Prepend some Text ("foobar") and a new HTML element ("
==><b>
foorbarbold</b>
)span.insertBefore("foobar<b>foobarbold</b>")
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
Try this:
$('#parent').html($('#subchildtext')).prepend('foobar<b>foodbarbold</b>');
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)
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
精彩评论