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>)