Get specific node text after element

I am trying to capture a specific line, "(TEXT 1)", "(TEXT 2)", etc. I can not 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 already tried this and this .

I can't seem to get the specific "(TEXT n)". Ideally, I would like to get a specific "(TEXT n)". Sort of:

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

How can I get a specific string with javascript or jQuery?

+4
source share
4 answers

As follows from your post, if you want to create your own method .nextText(), simply enter the following brother into the property property of the DOM element: nodeValue

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

.eq(), :

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

, , :

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

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

( OP ), .nextTextUntil():

$.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;
};

:

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

:

(TEXT 1 MORE TEXT)

HTML:

<a class="more" href="/e1">Event 1</a> (TEXT 1 <em>MORE TEXT</em>)
+5

nextSibling DOMElement, sibling. :

console.log($('.more')[0].nextSibling.nodeValue)); // = '(TEXT 1)'

, textNode .more 1 2.

+2

, ?

https://jsfiddle.net/xhp86ygq/

document.querySelector('.more').nextSibling.nodeValue

, , node:

getNextTextnodeValue = function(element) {
    return element.nextSibling.nodeValue;
};

, jQuery, , , ( , jQuery).

+2

, , jQuery , :

$.fn.getTextNodes = function(contentText) {
  return $(this).find(":not(iframe)").addBack().contents().filter(function() {
    return this.nodeType == 3 && this.nodeValue.indexOf(contentText) != -1;
  });
};

$(function () {
  var result = $('#areaWhereToSearch').getTextNodes('(TEXT 1)');
  if (result.length == 1) {
    $('#result').text($('#areaWhereToSearch').getTextNodes('(TEXT 1)')[0].nodeValue);
  }
});
<script src="//code.jquery.com/jquery-1.11.3.js"></script>


<div id="areaWhereToSearch">
    <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>
</div>
<p id="result"></p>
Hide result
+1

Source: https://habr.com/ru/post/1621535/


All Articles