1. 程式人生 > >jq獲取元素內文字,但不包括其子元素內的文字值的方法,不包括後代

jq獲取元素內文字,但不包括其子元素內的文字值的方法,不包括後代

權宣告:本文為博主原創文章,未經博主允許不得轉載。    https://blog.csdn.net/zhangwenwu2/article/details/78365667 <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; ---------------------  作者:zhangwenwu的前端小站  來源:CSDN  原文:https://blog.csdn.net/zhangwenwu2/article/details/78365667?utm_source=copy  版權宣告:本文為博主原創文章,轉載請附上博文連結!