如何使用jQuery选择文本节点?

2021年3月20日17:23:59 发表评论 1,319 次浏览

文本节点是一种节点类型, 表示元素内部的实际文本。通过选择所有节点并使用jQuery, 可以使用jQuery选择任何元素的textNodes。过滤()检查nodeType属性的方法。

首先使用jQuery选择器选择必需的元素。的内容()方法用于所选元素。此方法用于返回包含所有文本和注释节点的元素的直接子代。

的过滤()在这些返回的元素上使用方法来仅过滤所需的文本节点。自定义过滤器功能会检查nodeType节点的属性返回等于节点。TEXT_NODE值。

" Node.TEXT_NODE"值用于从其他节点识别文本节点。可替代地, 整数值" 3"也可以用于识别文本节点。现在, filter()方法将仅返回属于textNodes的节点。因此, 此方法可用于选择任何元素的textNodes。

语法如下:

selectedElement = $( "elementRequired" ).contents();
 
textNodes = selectedElement.filter( function () {
   return this .nodeType === Node.TEXT_NODE;
});

例子:

<!DOCTYPE html>
< html >
      
< head >
     < title >
         How to select text nodes using jQuery?
     </ title >
      
     < script src =
         "https://code.jquery.com/jquery-3.3.1.min.js" >
     </ script >
</ head >
  
< body >
     < h1 style = "color: green" >
         lsbin
     </ h1 >
      
     < b >
         How to select text nodes using jQuery?
     </ b >
      
     < p class = "example" >
         This is line 1< br >
         This is line 2< br >
         This is line 3
     </ p >
      
     < button onclick = "getTextNodes()" >
         Click to get Text Nodes
     </ button >
      
     < script type = "text/javascript" >
         function getTextNodes() {
             selectedElement = $(".example").contents();
          
             textNodes = selectedElement.filter(function ()
             {
                 return this.nodeType === Node.TEXT_NODE;
             });
              
             console.log(textNodes);
         }
     </ script >
</ body >
  
</ html >

输出如下:

显示:

textnodes-display

安慰:

文本节点控制台

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: