這具體的例子是很容易的,因爲目標文本節點是其父的最後一個孩子;看評論:
// 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>
參見:
從哪裏你想在哪裏被包裹在跨度? –
你可以添加你想要的id範圍,然後用JS或JQuery獲得這個範圍,並將它添加到你的班級myspan – sidanmor
@JayGhosh:很明顯,但只有當你向右滾動時 - 有一個'
'標籤,然後說它應該是紅色的文字。 –