2016-12-03 55 views
1

有没有办法在使用jQuery或Javascript的<span>标签中包装文本的最后一行?使用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

从哪里你想在哪里被包裹在跨度? –

+0

你可以添加你想要的id范围,然后用JS或JQuery获得这个范围,并将它添加到你的班级myspan – sidanmor

+0

@JayGhosh:很明显,但只有当你向右滚动时 - 有一个'
'标签,然后说它应该是红色的文字。 –

回答

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);
#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>

参见:

+1

作为一个方面说明,jQuery示例可以使用'$ .fn.wrap()'方法简化,例如:'div .contents()。last()。wrap(span);' –

+0

@ A.Wolff **非常好的一点,折叠在上面。 –

相关问题