有没有办法使用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 :(得分: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);
&#13;
#myspan{
color: #db1926;
}
&#13;
<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>
&#13;
或者使用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);
&#13;
#myspan{
color: #db1926;
}
&#13;
<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>
&#13;
作为A.Wolff points out,使用wrap
可以缩短批次:
$("#myDiv").contents().last().wrap('<span id="myspan"></span>');
&#13;
#myspan{
color: #db1926;
}
&#13;
<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>
&#13;
请参阅: