使用jQuery或Javascript添加<span>标签?

时间:2016-12-03 13:09:29

标签: javascript jquery

有没有办法使用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>

1 个答案:

答案 0 :(得分:4)

该具体示例非常简单,因为目标文本节点是其父节点中的最后一个子节点;见评论:

&#13;
&#13;
// 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;
&#13;
&#13;

或者使用jQuery:

&#13;
&#13;
// 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;
&#13;
&#13;

作为A.Wolff points out,使用wrap可以缩短批次

&#13;
&#13;
$("#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;
&#13;
&#13;

请参阅:

相关问题