2016-12-03 56 views
1

有沒有辦法在使用jQuery或Javascript的<span>標籤中包裝文本的最後一行?使用jQuery或Javascript添加<span>標籤?

#myspan{ 
 
    color: #db1926; 
 
}
<div id="myDiv">Here is some text, of which I want the last line to be wrapped in span-tags with id="myspan".<br>If it works this line will color red. 
 
</div>

+0

從哪裏你想在哪裏被包裹在跨度? –

+0

你可以添加你想要的id範圍,然後用JS或JQuery獲得這個範圍,並將它添加到你的班級myspan – sidanmor

+0

@JayGhosh:很明顯,但只有當你向右滾動時 - 有一個'
'標籤,然後說它應該是紅色的文字。 –

回答

4

這具體的例子是很容易的,因爲目標文本節點是其父的最後一個孩子;看評論:

// Create the span, give it its ID 
 
var span = document.createElement("span"); 
 
span.id = "myspan"; 
 

 
// Get the div 
 
var div = document.getElementById("myDiv"); 
 

 
// Move the last child of the div into the span 
 
span.appendChild(div.childNodes[div.childNodes.length - 1]); 
 

 
// Append the span to the div 
 
div.appendChild(span);
#myspan{ 
 
    color: #db1926; 
 
}
<div id="myDiv">Here is some text of which I want the last line to be wrapped in span-tags with as id="myspan".<br>If it works this line will color red. 
 
</div>

或者使用jQuery:

// Create the span, give it its ID 
 
var span = $("<span>").attr("id", "myspan"); 
 

 
// Get the div 
 
var div = $("#myDiv"); 
 

 
// Move the last child of the div into the span 
 
span.append(div.contents().last()); 
 

 
// Append the span to the div 
 
div.append(span);
#myspan{ 
 
    color: #db1926; 
 
}
<div id="myDiv">Here is some text of which I want the last line to be wrapped in span-tags with as id="myspan".<br>If it works this line will color red. 
 
</div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

由於A.Wolffpoints out,即可以使用短一個很多:

$("#myDiv").contents().last().wrap('<span id="myspan"></span>');
#myspan{ 
 
    color: #db1926; 
 
}
<div id="myDiv">Here is some text of which I want the last line to be wrapped in span-tags with as id="myspan".<br>If it works this line will color red. 
 
</div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

參見:

+1

作爲一個方面說明,jQuery示例可以使用'$ .fn.wrap()'方法簡化,例如:'div .contents()。last()。wrap(span);' –

+0

@ A.Wolff **非常好的一點,摺疊在上面。 –

相關問題