Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更改HTML标记,包括同一标记的子标记_Javascript_Jquery_Html_Tags - Fatal编程技术网

Javascript 更改HTML标记,包括同一标记的子标记

Javascript 更改HTML标记,包括同一标记的子标记,javascript,jquery,html,tags,Javascript,Jquery,Html,Tags,我用它来改变一个HTML标记,当我试图更新一些HTML标记时,我在到达同一标记的父标记时遇到了麻烦 例如,将span更新为div应导致: <div> <div>div within a div</div> </div> div中的div 但它的出现是这样的: <div> <span>div within a div</span> </div> div中的div 作为参考,这

我用它来改变一个HTML标记,当我试图更新一些HTML标记时,我在到达同一标记的父标记时遇到了麻烦

例如,将span更新为div应导致:

<div>
    <div>div within a div</div>
</div>

div中的div
但它的出现是这样的:

<div>
    <span>div within a div</span>
</div>

div中的div
作为参考,这是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);
});
var divTag='div';
$('span')。每个(函数(){
var outer=this.outerHTML;
//将所有跨度标记替换为divTag类型
var regex=new RegExp('
var div=$(“div”);
var html=div[0].outerHTML.replace(/div(?=>)/gi,“span”);
log(html);
div.replaceWith(html);

div中的div

在@guest271314解决方案中进行一些转换,以避免替换内容,只替换HTML标记

var div = $("div");
var html = div[0].outerHTML.replace(/<div/g, "<span");
div.replaceWith(html);
var div=$(“div”);

var html=div[0].outerHTML.replace(/Thank you,这正是我想要的!我注意到的一个问题是,如果您正在更新像a或a-its这样的内容,则会拉取内部html并复制它。请参阅fiddle感谢您的响应@guest271314!@Imgonzalves jQuery未在加载;请参阅是的,我的错。
$("div").each(function(){
    var html = $(this)[0].outerHTML.replace(/<div/g, "<span");
    $(this).replaceWith(html);
});