[英]Add <span> tags using jQuery or Javascript?
有沒有辦法使用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>
該特定示例非常容易,因為目標文本節點是其父級中的最后一個子級。 看評論:
// 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.Wolff所 指出的那樣 ,使用wrap
可以縮短很多時間:
$("#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>
看到:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.