javascript - 从 DOM 解析 HTML

标签 javascript html xpath

我正在尝试从以下 HTML 代码中解析替代文本,这些代码是我从 Xpath 中获得的,表示为“FIRST_RECORD_LINK”。

<img data-aria-label-part="" src="https://pbs.twimg.com/media/Dc10VX_UwAAJxPM.jpg" alt="Millenials are more likely than Baby Boomers to be living with a disability. 
Provided by the Center for Talent Innovation Disability Inclusion Report."> 

我的 javascript 代码如下所示:

var FIRST_RECORD_LINK = '//*[@id="stream-item-tweet-999772032685527042"]/div[1]/div[2]/div[3]/div/div/div/div/img';
var FIRST_RECORD = document.evaluate(FIRST_RECORD_LINK, document, 
    null, XPathResult.ANY_TYPE, null).iterateNext();
console.log(FIRST_RECORD); 
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(FIRST_RECORD,"text/html");
console.log(xmlDoc.getElementsByTagName("img")[0].childNodes[0].getAttribute("alt"));

我做错了什么?对于没有使用代码框,我提前表示歉意,我有视力障碍,而且它们不支持我的屏幕阅读器。

最佳答案

通过评估 xpath 获得 FIRST_RECORD 中的 img 后,您可以使用 getAttribute 读取 alt 属性:

FIRST_RECORD.getAttribute('alt');

查看一个工作示例(使用更新的 xpath,以便它在 stackoverflow 中工作):

// The following path was modified to work in stackoverflow
var FIRST_RECORD_LINK = '//img';
var FIRST_RECORD = document.evaluate(FIRST_RECORD_LINK, document, null, XPathResult.ANY_TYPE, null).iterateNext();
console.log(FIRST_RECORD);
console.log(FIRST_RECORD.getAttribute('alt'));
<img data-aria-label-part="" src="https://pbs.twimg.com/media/Dc10VX_UwAAJxPM.jpg" alt="Millenials are more likely than Baby Boomers to be living with a disability. 
Provided by the Center for Talent Innovation Disability Inclusion Report.">

关于javascript - 从 DOM 解析 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50726279/

相关文章:

javascript - 命名函数是 jsx Prop 的好习惯吗?

javascript - 将 fetch 的结果发送到程序的另一部分

javascript - 复制动态文本框上的下拉值

xml - 使用 XSLT 为每个空字段传递文本值

xslt - XPath表达式选择除特定列表之外的所有XML子节点?

c# - 如何在 Linq-to-XML 中按路径查找 XML 节点

javascript - 如果元素在 <form> 中,为什么 clone() 太慢?

javascript - 如果条件在 jquery 中不起作用

html - 无法使用 CSS 重置更改正文背景颜色

javascript - 如何使我的 Canvas 外菜单滚动?