I'm using this previously answered question about altering an HTML tag and while trying to update some HTML tags, I'm having trouble reaching the tags within a parent of the same tag.
For example, updating a span to a div should result in:
<div>
<div>div within a div</div>
</div>
But is showing up like:
<div>
<span>div within a div</span>
</div>
And for reference, this is the js:
var divTag = 'div';
$('span').each(function() {
var outer = this.outerHTML;
// Replace all span tags with the type of divTag
var regex = new RegExp('<' + this.tagName, 'i');
var newTag = outer.replace(regex, '<' + divTag);
// Replace closing tag
regex = new RegExp('</' + this.tagName + '>$', 'i');
newTag = newTag.replace(regex, '</' + divTag + '>');
$(this).replaceWith(newTag);
});
Any help is greatly appreciated! Thanks!
A little transformation in @guest271314 solution, to avoid replace the content, only replace the HTML tags.
var div = $("div");
var html = div[0].outerHTML.replace(/<div/g, "<span");
div.replaceWith(html);
FIDDLE: https://jsfiddle.net/lmgonzalves/31c5bebx/1/
EDIT:
$("div").each(function(){
var html = $(this)[0].outerHTML.replace(/<div/g, "<span");
$(this).replaceWith(html);
});
var div = $("div"); var html = div[0].outerHTML.replace(/div(?=>)/gi, "span"); console.log(html); div.replaceWith(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div> <div>div within a div</div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.