Javascript JQuery用Div替换Span
我有一个html元素:Javascript JQuery用Div替换Span,javascript,jquery,html,Javascript,Jquery,Html,我有一个html元素: <span id="4" style="display: block"> <div> <span>ttttttt</span> <p>ttttttt</p> </div> </span> ttttttt ttttttt 我想将最外层的跨度更改为div,因此看起来像: <div id="4" style="display: block">
<span id="4" style="display: block">
<div>
<span>ttttttt</span>
<p>ttttttt</p>
</div>
</span>
ttttttt
ttttttt
我想将最外层的跨度更改为div,因此看起来像:
<div id="4" style="display: block">
<div>
<span>ttttttt</span>
<p>ttttttt</p>
</div>
</div>
ttttttt
ttttttt
我在线查看并找到了解决方案:
var myNodes = $('[type="type1"]')
myNodes[0].replaceWith(function() {
return '<div>'+$(this).html()+'</div>';
});
var myNodes=$('[type=“type1”]'))
myNodes[0]。替换为(函数(){
返回“”+$(this).html()+“”;
});
但是,它不起作用。截图如下:
我能得到一些帮助吗
Span不能包含div(我知道您为什么要更改它 而且我永远不会使用数字ID 试试这个
$(“#Span4”).replacetwith(函数(){
返回$(“”){
“样式”:此.getAttribute(“样式”),
“id”:这个是
}).html($(this.html());
})
ttttttt
ttttttt
使用JQuery
它将如下所示:
var nestedSpan = $('#4 span:first');
var nestedSpanText = nestedSpan.text();
nestedSpan.replaceWith('<div>' + nestedSpanText + '</div>');
$('4 div').unwrap().wrap('');
$('4 div').unwrap().wrap('');
ttttttt
ttttttt
为了使用.replaceWith()
您的元素必须用jQuery包装。如果我们忽略了元素的id不应该以数字开头这一事实,那么它将是$(“#4”)。replaceWith(
谢谢!我使用var myNodes=$('[type=“type1”]')来选择节点。为什么您认为$('[type=“type1”]'))
将选择跨度?但无论如何,如果您想使用jQuery数组myNodes
,如上所述,您需要在jQuery中封装元素,类似于$(myNodes[0])。replaceTwith
或myNodes.eq(0)。replaceTwith
@CarstenLøvboAndersen数值ID在html5中不被禁止:)当我们通过此代码更改标记时,我们:1.复制嵌套的html 2.销毁旧标记3.在其上创建新标记place.4.将内部html放回原位。因此,如果您想对该元素执行更多操作,则需要重新选择它。我建议您设置自定义id
以重新选择:返回“+$(this).html()+”
并按它进行选择,如:$(“#嵌套span”).outerHtml
var nestedSpan = $('#4 span:first');
nestedSpan.replaceWith(function() {
return '<div>'+$(this).html()+'</div>';
});
$('#4 div').unwrap().wrap('<div id="4" style="display: block;"></div>');