开发者

Replace an HTML element with some HTML contained in a string

开发者 https://www.devze.com 2023-03-28 20:55 出处:网络
Let\'s say I have this portion of HTML document: <div>hello world <span id=\"test\"></span></div>

Let's say I have this portion of HTML document:

<div>hello world <span id="test"></span></div>

In s开发者_开发百科traight JavaScript, I need to replace the span with some HTML content contained in a string like '<span>other</span> yo <a href="www.google.ca">google</a>'

So the end result be like:

<div>hello world <span>other</span> yo <a href="www.google.ca">google</a></div>

The problem I'm facing is that the HTML string can contain any number of tags at its "root". So it is not a 1 to 1 replacement of tags.

I need to do that in straight JavaScript (no jQuery).

If anyone can help!

Thanks


What is the reason you can't just set the innerHTML of <span id="test">? There's no harm in having the extra span...

If you really need to remove the outer span, you can just insert all the childNodes before it.

var html = '<span>other</span> yo <a href="www.google.ca">google</a>';

var removeMe = document.getElementById('test');
removeMe.innerHTML = html;

var child;
while(child = removeMe.childNodes[0]) {
    removeMe.parentNode.insertBefore(child, removeMe);
}

removeMe.parentNode.removeChild(removeMe);

See http://jsfiddle.net/4tLVC/1/


can't you use

 var span = document.getElement...('test')
 div.getElementById('yourDiv').removeChild(span)

or actually you can do

span.parentNode.removeChild(span)

this should work to. After that

 div.innerHTML += 'your cool <span>content></span>'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号