Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text after certain element (JavaScript or JQuery) [duplicate]

Could some one give me some guidance on what's the best way to do this.

I'm trying to get all the text which is after ".main"

I know this might be simple, but it's been picking at my brain all day just before Christmas. So i thought instead of stressing myself out, I would look for some guidance.

The example code only brings back the Text in P tag but i'd like to bring back Text not in it's own element and the 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's own element
  <p> Text in P tag </p>
</div>
like image 335
YaBCK Avatar asked Dec 21 '17 15:12

YaBCK


2 Answers

It's because Text not in it's own element is considered a text node, therefore next() will target the <p/> tag, being that it's an HTMLElement. If you were to go native you'd use a combination of nextSibling, which is agnostic of the two node types and nextElementSibling, which as it's method name implies, grabs the next sibling 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's own element
  <p> Text in P tag </p>
</div>
like image 62
Carl Edwards Avatar answered Oct 19 '22 08:10

Carl Edwards


The simplest way to achieve this is to clone() the container, remove the .main element from it, then get the text(), like this:

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's own element
  <p> Text in P tag </p>
</div>

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

like image 44
Rory McCrossan Avatar answered Oct 19 '22 09:10

Rory McCrossan