<li id="listItem"> This is some text <span id="firstSpan">First span text</span> <span id="secondSpan">Second span text</span> </li>
假設上面一段代碼,我們想獲取 'This is some text' 這段文本值,
jq提供的方法是 text(),但結果打印的是 ‘This is some textFirst span textSecond span text’,
可見text()方法返回的值是元素內所有子元素內的文本值,那么如果只想獲取 'This is some text' 怎么辦呢?
有下面幾種方法:
1、jq方法
$("#listitem")
.clone() //復制元素
.children() //獲取所有子元素
.remove() //刪除所有子元素
.end() //回到選擇的元素
.text();//獲取文本值
2、jq方法
$("#listItem").contents().filter(function(){
return this.nodeType == 3;
})[0].nodeValue = "The text you want to replace with"
3、js方法
document.getElementById("listItem").childNodes[0].nodeValue;