想从网页获取特定值

时间:2021-09-29 17:07:30
<div class = "foo">
   <span class = "foo2" > HeaderText</span>
   <br>
   "
        TEXT I WANT"

I have been trying to get it in JS.

我一直试图在JS中得到它。

var NEEDED= document.getElementsByClassName('foo')[0].textContent 

Also tried foo2 and innerText, innerHTML

还尝试了foo2和innerText,innerHTML

I just don't know how to call something that isn't tied directly to an ID or Class

我只是不知道如何调用与ID或类没有直接联系的东西

1 个解决方案

#1


0  

What you are trying to do is going to be very difficult if the HTML is subject to change. Even nodes that aren't surrounded by an HTML element are still childNodes of it's parent, so you can get this by looking at:

如果HTML可能会发生变化,那么您要做的就是非常困难。即使没有HTML元素包围的节点仍然是它父节点的childNodes,所以你可以通过查看:

var needed = document.getElementsByClassName('foo')[0].childNodes[4].nodeValue;

You might need to write a function that filters through all of the childNodes and finds one with nodeType 3 (text nodes), then ignore all of the ones that are just blank whitespace.

您可能需要编写一个过滤所有childNodes的函数,并找到一个带有nodeType 3(文本节点)的函数,然后忽略所有只是空白空格的函数。

var needed = document.getElementsByClassName('foo')[0].childNodes[4].nodeValue;
document.write("The text is: " + needed);
<div class = "foo">
   <span class = "foo2" > HeaderText</span>
   <br>
   TEXT I WANT
</div>

#1


0  

What you are trying to do is going to be very difficult if the HTML is subject to change. Even nodes that aren't surrounded by an HTML element are still childNodes of it's parent, so you can get this by looking at:

如果HTML可能会发生变化,那么您要做的就是非常困难。即使没有HTML元素包围的节点仍然是它父节点的childNodes,所以你可以通过查看:

var needed = document.getElementsByClassName('foo')[0].childNodes[4].nodeValue;

You might need to write a function that filters through all of the childNodes and finds one with nodeType 3 (text nodes), then ignore all of the ones that are just blank whitespace.

您可能需要编写一个过滤所有childNodes的函数,并找到一个带有nodeType 3(文本节点)的函数,然后忽略所有只是空白空格的函数。

var needed = document.getElementsByClassName('foo')[0].childNodes[4].nodeValue;
document.write("The text is: " + needed);
<div class = "foo">
   <span class = "foo2" > HeaderText</span>
   <br>
   TEXT I WANT
</div>