How to get only direct text without tags with jQuery in HTML

后端 未结 8 484
忘了有多久
忘了有多久 2020-11-27 06:15

I\'ve got an HTML:

1)TEXT THAT I ONLY NEED

some par

    ..

I need only

相关标签:
8条回答
  • 2020-11-27 06:33

    This code works for me:

    var el = $("<div/>");
    el.html(text).children().remove();
    return el.text();
    
    0 讨论(0)
  • 2020-11-27 06:35

    Yet another approach With vanila/pure JavaScript

    const el = document.getElementById('element');
    const elNodes = el.childNodes;
    let plainText = "";
    for(i=0;i<elNodes.length;i++){
       if(elNodes[i].nodeName == '#text'){
         plainText+=elNodes[i].textContent;
       }
    }
    console.log(plainText); // prints TEXT THAT I ONLY NEED
    <!-- html -->
    <div id='element'>
      <strong>1)</strong>TEXT THAT I ONLY NEED
      <p>some par</p>
      <ul>..</ul>
    </div>

    0 讨论(0)
  • 2020-11-27 06:44

    well, if you use jQuery, you would do

    $('.selector').text();
    

    more info and examples here

    edit: I just saw you want the text that is not in any tags - well this is not directly possible (fact is, that every text inside a html document is inside some HTML tags.)

    In this case I would try to change the markup (easiest way), so the desired text is within html tags. If this is not possible, you use the above mentioned text() method to get the whole text from the parent element, and after you have to subtract the pieces you dont want.

    see http://jsfiddle.net/3SSAR/1/ for an example of how to subtract the strings..

    just remember to use substr and not - to subtract strings in javascript

    0 讨论(0)
  • 2020-11-27 06:44
    var name = $($(YourElementOuterHTML)).children().remove().end().text();
    

    example:-

    var name = $($(li).find("a").get(0).outerHTML).children().remove().end().text(); 
    
    0 讨论(0)
  • 2020-11-27 06:47

    The best way is to .clone() your object, .remove() all of its .children(), then go back to the object using .end() and finally get the .text().

    The method is described in this blog post.

    $("strong")
            .clone()    //clone the element
            .children() //select all the children
            .remove()   //remove all the children
            .end()  //again go back to selected element
            .text();    //get the text of element
    
    0 讨论(0)
  • 2020-11-27 06:51

    Your markup isn't the greatest for this. If you wrapped the text you want with a span such as:

    <span class="gettext">TEXT THAT I NEED</span>
    

    You could use $('.gettext').text(); in jQuery.

    0 讨论(0)
提交回复
热议问题