简体   繁体   English

通过xpath和html文档中的javascript获取TAG中的文本

[英]Getting a text inside a TAG via xpath and javascript in a html document

So, I'm trying to get the text inside of a tag in a list. 因此,我试图将文本添加到列表中的标记内。

Let me say I have something like 我说我有类似的东西

<div>text1</div>
<div>text2</div>
<div>text3</div>
<div>text4</div>
<div>text5</div>
<div>text6</div>

so, I want to get the "number" of the DIV who matchs "text4" for example, so it will return a "4". 因此,我想获取与“ text4”匹配的DIV的“数字”,因此它将返回“ 4”。 I cant modify the html, there is no class or ID in the divs. 我无法修改html,div中没有​​类或ID。 Maybe I can get the innerHTML of a div? 也许我可以获得div的innerHTML? But how will I put all the divs inside a vector or something like that? 但是,如何将所有div放在向量之类的东西中呢?

Thanks in advance 提前致谢

Here is a way of working with elements by tag name: 这是按标记名称使用元素的一种方法:

var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
    var html = divs[i].innerHTML;
    console.log(html);
}

DEMO: http://jsfiddle.net/DEJty/ 演示: http : //jsfiddle.net/DEJty/

In XPath this is 在XPath中,这是

count(//div[.='text4']/preceding-sibling::*) + 1

Incidentally, 'text4' is not "in" any tag; 顺便说一句,“ text4”不是“在”任何标签中。 it is between two tags, a start tag and an end tag. 它位于两个标签之间,一个开始标签和一个结束标签。 I mention this because you will find it easier to understand specifications and error messages if you learn the official vocabulary. 我之所以这样说是因为,如果您学习官方词汇,将会发现更容易理解规格和错误消息。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM