search

Home  >  Q&A  >  body text

How to get the text node of an element?

<p><pre class="brush:php;toolbar:false;"><div class="title"> I am text node <a class="edit">Edit</a> </div></pre> <p>I want to get the "I am text node", don't want the "edit" tag to be removed, and need a cross-browser solution. </p>
P粉518799557P粉518799557506 days ago618

reply all(2)I'll reply

  • P粉148434742

    P粉1484347422023-08-25 09:11:57

    You can use the following method to get the nodeValue of the first child node

    $('.title')[0].childNodes[0].nodeValue

    http://jsfiddle.net/TU4FB/

    reply
    0
  • P粉239164234

    P粉2391642342023-08-25 00:26:46

    var text = $(".title").contents().filter(function() {
      return this.nodeType == Node.TEXT_NODE;
    }).text();

    This takes the content of the selected element and applies the filter function to it. The filter function returns only text nodes (i.e. those with nodeType == Node.TEXT_NODE).

    reply
    0
  • Cancelreply