I'm trying to toggle between two chunks of HTML开发者_如何学Go, a span
and an anchor
. For example:
<span class="current">Demo</span>
toggle with:
<a href="http://someurl/" class="demo">Demo</a>
I've tried the following:
$(spanDemo).html('<a href="http://someurl/" class="demo">Demo</a>');
$(anchorDemo).html('<span class="current">Demo</span>');
However, the elements get wrapped inside each other, and the DOM result is:
<span class="current"><a href="http://someurl/" class="demo">Demo</a></span>
and
<a href="http://someurl/" class="demo"><span class="current">Demo</span></a>
THE QUESTION IS: How can I use replace the entire wrap, instead of wrapping these HTML chunks together?
Thanks!
Use replaceWith
$('.current').replaceWith('<a href="http://someurl/" class="demo">Demo</a>');
$('.demo').replaceWith('<span class="current">Demo</span>');
Set up a div with a class instead, and then set it's contents.
Instead of worrying about removing and adding, and since you're using jQuery, you could also hide and show with both "on" the page, simply hidden until needed.
Wrap each element in a div
. When you call html()
you are replacing the innerHTML of that element.
Change your HTML to something like this:
<div id="span">
<span class="current">Demo</span>
</div>
<div id="a">
<a href="http://someurl/" class="demo">Demo</a>
</div>
And then toggle with these selectors:
$('#span').html('<a href="http://someurl/" class="demo">Demo</a>');
$('#a').html('<span class="current">Demo</span>');
精彩评论