Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get particular text node after an element

I'm trying to grab a particular string, " (TEXT 1)", " (TEXT 2)", etc. I cannot change the HTML.

When I do this:

$(this).parent().html(); // $(this) is equivalent to $('a.more').

I get:

<a class="more" href="/e1">Event 1</a> (TEXT 1)<br>
<a class="more" href="/e2">Event 2</a> (TEXT 2)<br>
<a class="more" href="/e3">Event 3</a> (TEXT 3)<br>

I've already tried this and this.

I can't seem to get a particular "(TEXT n)". Ideally I'd like to get a particular "(TEXT n)". Something along the lines of:

$('a.more').nextText(1); // this would return " (TEXT 2)"

How can I get a particular string with either JavaScript or jQuery?

like image 787
rotaercz Avatar asked Dec 25 '22 11:12

rotaercz


1 Answers

As your post implies, if you want to create a custom .nextText() method, just access the nodeValue property of the DOM element's next sibling:

$.fn.nextText = function() {
  return this.length ? this[0].nextSibling.nodeValue : null;
};

Then you can use the .eq() method to get the element by its index and use the custom method:

Example Here

var text = $('.more').eq(0).nextText();
console.log(text); // (TEXT 1)

If you want to add a parameter to pass the index of the element you want to retrieve the text from:

Example Here

$.fn.nextText = function(index) {
  return this.length ? this[index || 0].nextSibling.nodeValue : null;
};

var text = $('.more').nextText(1);
console.log(text); // (TEXT 2)

If you want to get multiple elements and text nodes until a specific element (as the OP did in the comments), you can use this custom .nextTextUntil() method:

Example Here

$.fn.nextTextUntil = function(until) {
  var text = '', next;

  if (this.length) {
    next = this[0].nextSibling;

    while (next !== null && until && !$(next).is(until)) {
      text += next.nodeValue || next.textContent;
      next = next.nextSibling;
    }
  }

  return text;
};

Usage:

$('.more').eq(0).nextTextUntil('.more');

Would return:

(TEXT 1 MORE TEXT)

Based on the following HTML:

<a class="more" href="/e1">Event 1</a> (TEXT 1 <em>MORE TEXT</em>)
like image 80
Josh Crozier Avatar answered Dec 26 '22 23:12

Josh Crozier