这具体的例子是很容易的,因为目标文本节点是其父的最后一个孩子;看评论:
// 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:很明显,但只有当你向右滚动时 - 有一个'
'标签,然后说它应该是红色的文字。 –