2

Lets say I have the html as below:

<h3 class="search-result-title">
            This is a test
            <small class="search-result-subtitle">
                Some more explanation
            </small>
        </h3>

How can I filter the text This is a test without the small ?

Edit: I am using it with the symfony Dom Crawler.

So I have filter(a. h3 search-result-title); But I don't want the contents of the small element.

sanders
  • 10,794
  • 27
  • 85
  • 127

5 Answers5

1

You can extract the content using filter() by giving small element as the parameter and then remove() it.

$('.search-result-title').contents().filter("small").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="search-result-title">
   This is a test
   <small class="search-result-subtitle">
      Some more explanation
   </small>
 </h3>
m4n0
  • 29,823
  • 27
  • 76
  • 89
1

You can use this code to get text of h3 element only.

document.querySelector('.search-result-title').firstChild.textContent
Alpesh Panchal
  • 1,723
  • 12
  • 9
0

wrap This is a test with span tag and user $('h3.search-result-title>span:first-child') to select.

Manivannan
  • 3,074
  • 3
  • 21
  • 32
0

I saw that you were using jQUery so I found this : text without child

You can do something like this :

$.fn.ignore = function(sel){ return this.clone().find(sel||">*").remove().end(); }; console.log($("h3.search-result-title").ignore("small").text().trim());

this will return 'This is a test'

Hope it helps !

Community
  • 1
  • 1
Pipo
  • 193
  • 1
  • 1
  • 9
0

You can use .filter() the .contents():

var txt = $('h3.search-result-title').contents().filter(function(){
    return this.nodeType == 3; 
 });
Jai
  • 74,255
  • 12
  • 74
  • 103