以下是嵌套div的HTML格式代码
<div>
<div>
Text 1
<div>
Text 2
</div>
</div>
</div
我想使用jquery或javascript
<div>
<div>
<span class="custom">Text 1</span>
<div>
<span class="custom">Text 2</span>
</div>
</div>
</div
答案 0 :(得分:7)
$('div').contents().filter(function() {
return this.nodeType == 3;
}).wrap("<span class=custom></span>")
&#13;
.custom {
color: red
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
Text 1
<div>
Text 2
</div>
</div>
</div>
&#13;
.wrap()
来换算span 答案 1 :(得分:1)
$([your element selector here]).contents()
// get all text nodes
.filter(function(){return this.nodeType === 3})
// wrap in a span element
.wrap('<span />')
// add class custom to each element
.addClass('custom');