简体   繁体   English

如何获取2个元素之间的文本

[英]How can I get the text between 2 elements

<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]")? 如何在元素之间撤回文本(不是元素的内部文本,在这种情况下我应该得到“[我想得到这个文本]”)?

DEMO DEMO

I think the simplest way would be to deal with the native dom elements: 我认为最简单的方法是处理本机dom元素:

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

Note that var text = textNode.nodeValue; 注意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: 一种方法是将部件包含在span标签中并获取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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在两个独立标签之间获取 HTML 元素 - How can I get HTML elements between two independent tags 如何获取网页内元素中文本的字体大小 - How can I get the font size of text in elements within a webpage 如何获取填充的li元素之间的空li元素的长度? - How can i get the length of empty li elements between to populated li elements? 我怎样才能让浏览器允许行内元素之间的换行符(它们之间没有空格)? - How can I get the browser to allow line-breaks between inline elements (with no spaces between them)? 如何设置两个之间的文本样式 <br> 元素? - How can I style a part of text which is between two <br> elements? 如何选择两个元素之间的所有元素 - how can I select all elements between two elements 提交按钮后刷新dom后如何获取元素内部文本? - How can I get elements inner text after dom is being refreshed after the submit button? 如何使用 JQuery 从远处元素中获取 img src 和文本? - How can I get img src and text from distant elements using JQuery? 如何在元素P中获取文本,用javascript DOM排除它们可能的子元素A? - How can I get the text inside an element P excluding their possible child elements A with javascript DOM? 如何获得所选内容中所有文本元素的边界框值? - How can I get the bounding box values of all the text elements in a selection?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM