最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I get the text between 2 elements - Stack Overflow

programmeradmin0浏览0评论
<div class="container">
  <a href="#" class="link">asd</a>
  [I want get this text]
  <a href="#" class="link">asd</a>
  Anouther text i dont need.
</div>

How can I withdraw the text between elements (not the inner text of elements, in this case I should get "[I want get this text]")?

<div class="container">
  <a href="#" class="link">asd</a>
  [I want get this text]
  <a href="#" class="link">asd</a>
  Anouther text i dont need.
</div>

How can I withdraw the text between elements (not the inner text of elements, in this case I should get "[I want get this text]")?

Share Improve this question edited Jan 19, 2012 at 20:38 Mike Robinson 25.2k8 gold badges63 silver badges83 bronze badges asked Jan 19, 2012 at 20:35 FisherFisher 1,7942 gold badges19 silver badges38 bronze badges 3
  • 1 The text blocks are also nodes in the DOM tree, and would show up as part of the div.container's childNodes – Marc B Commented Jan 19, 2012 at 20:36
  • firstAnchor.nextSibling.data where firstAnchor is a reference to the fist A element. – Šime Vidas Commented Jan 19, 2012 at 20:39
  • Thanks Marc, I didn't thought that pure text is also a node in DOM – Fisher Commented Jan 19, 2012 at 20:48
Add a ment  | 

2 Answers 2

Reset to default 9

DEMO

I think the simplest way would be to deal with the native dom elements:

var a = $(".container a")[0];
var textNode = a.nextSibling;
var text = textNode.textContent;

Note that var text = textNode.nodeValue; will also work, but I'm not sure which is preferable.

One way is to enclose the part in a span tag and get the contents of the span:

<div class="container">
      <a href="#" class="link">asd</a>
      <span id="i_want_this">[I want get this text]</span>
      <a href="#" class="link">asd</a>
      Anouther text i dont need.
</div>

myVal = $("#i_want_this").html();
发布评论

评论列表(0)

  1. 暂无评论