![](/img/trans.png)
[英]How to wrap part of all text_node nodeValue in an html element?
[英]How to wrap all text in html with another element?
例如:
從
<div>
whats up!
<div> whats up2! </div>
thank you for your help
<div></div>
</div>
至
<div>
<span>whats up!</span>
<div><span> whats up2! </span></div>
<span>thank you for your help</span>
<div></div> <!---STAYS THE SAME -->
</div>
我如何在jQuery或純JavaScript中制作這樣的東西?
有這個HTML:
<div id="container" >
whats up!
<div> whats up2! </div>
thank you for your help
</div>
你可以這樣做:
var nodes = document.getElementById('container').childNodes;
$(nodes).each(function(ind, el){
if(el.nodeType == 3)
$(el).wrap('<span>');
else
$(el).wrapInner('<span>');
});
據我所知,你不能用jQuery獲取文本節點(如果我錯了請糾正我'),所以你可以用純JavaScript來獲取它們並使用jQuery的方法換行
為了完整起見,@ davids提供的解決方案擴展到更深層次結構,可以在“純”jquery中編寫如下
$('#container')
.find('*')
.andSelf()
.contents()
.filter(function() {
return this.nodeType == 3;
})
.wrap('<span>')
其內容如下:獲取#container及其所有正確DOM子項的完整內容,僅保留文本節點( nodeType == 3
)並將其包裝在<span>
。
請注意,如果應用於大型DOM樹,這將變得非常慢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.