Get text after a specific element (JavaScript or jQuery)

Can anyone give me some tips on how best to do this.

I try to get all the text that is after ".main"

I know that it can be simple, but he collected my brain all day shortly before Christmas. So I thought that instead of emphasizing myself, I would like to find some guidance.

The sample code returns only Text in P tag , but I would like to return Text not in it own element and p tag

 console.log($("#container").find(".main").next().text()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="container"> <div class="main"> WOOP IN MAIN </div> Text not in it own element <p> Text in P tag </p> </div> 
+7
javascript jquery
source share
2 answers

This is because Text not in it own element is considered a text node, so next() will target the <p/> that it is an HTMLElement . If you went to your native language, you would use a combination of nextSibling , which is an agnostic of the two types node and nextElementSibling , which, as the name of the method implies, captures the next element :

 const main = document.querySelector('.main'); const txt = [ main.nextSibling.textContent.trim(), main.nextElementSibling.textContent.trim() ]; console.log(txt) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="container"> <div class="main"> WOOP IN MAIN </div> Text not in it own element <p> Text in P tag </p> </div> 
+6
source share

The easiest way to achieve this is with the clone() container, remove the .main element from it, then get text() , for example:

 var text = $("#container").clone().find('.main').remove().end().text(); console.log(text.trim()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="container"> <div class="main"> WOOP IN MAIN </div> Text not in it own element <p> Text in P tag </p> </div> 

You can alternatively recursively go through the DOM nodes that follow the .main element, but this is much more complicated and gives the same result.

+8
source share

All Articles