获取元素后的特定文本节点

时间:2015-12-23 22:03:28

标签: javascript jquery html

我正在尝试抓取一个特定的字符串,“(文本1)”,“(文本2)”等等我无法更改HTML。

当我这样做时:

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

我明白了:

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

我已经尝试过thisthis

我似乎无法获得特定的“(TEXT n)”。理想情况下,我想得到一个特定的“(TEXT n)”。有点像:

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

如何使用JavaScript或jQuery获取特定字符串?

4 个答案:

答案 0 :(得分:5)

正如您的帖子所暗示的,如果您想创建自定义.nextText()方法,只需访问DOM元素的nodeValue property下一个兄弟:

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

然后你可以使用.eq()方法通过索引获取元素并使用自定义方法:

Example Here

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

如果要添加参数以传递要从中检索文本的元素的索引:

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)

如果要获取多个元素和文本节点,直到特定元素(如评论中的OP所做),您可以使用此自定义.nextTextUntil()方法:

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

用法:

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

会回来:

(TEXT 1 MORE TEXT)

基于以下HTML:

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

答案 1 :(得分:2)

您可以使用基础DOMElement的nextSibling方法来获取兄弟textNode。试试这个:

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

Example fiddle

请注意,要将textNode放在其他.more元素旁边,您可以将索引更改为12

答案 2 :(得分:2)

这似乎有效,或者我误解了你的确切问题?

https://jsfiddle.net/xhp86ygq/

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

现在,如果您需要一个为给定节点执行此操作的函数:

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

真的把它写进一个jQuery插件只会给代码添加大量的批量,你就什么也得不到,因为它不可链接(返回一个字符串,而不是一个jQuery对象)。

答案 3 :(得分:1)

我的建议,并非高效,但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>