【问题标题】:selecting an element by a tag name and class name通过标签名和类名选择元素
【发布时间】:2022-01-15 11:13:19
【问题描述】:

我正在尝试在具有已知类名的标头中捕获 a 标记。

检查元素:

<h3 class="c-card__title">
                    <a href="https://www.springer.com/book/9783030873233" data-track="click" data-track-action="clicked article" data-track-label="article-0">SARS-CoV-2 Spike Protein Convergent Evolution
                    </a>
                </h3>

我的代码:

var elements = document.getElementsByClassName("c-card__title").getElementsByTagName('a');
var vals = [];
for(var i=0;typeof(elements[i])!='undefined';vals.push(elements[i++].getAttribute('href')));
     for (var j = 0;typeof(vals[j])!='undefined'; ++j) {
     window.open(vals[j]);

我在浏览器控制台中运行它,但它给了我以下错误:

VM1065:4 Uncaught TypeError: document.getElementsByClassName(...).getElementsByTagName is not a function
    at <anonymous>:4:66

【问题讨论】:

  • 我今天早些时候读到了同样的问题。我记得是因为我评论了几件事,例如for(var i=0;typeof(elements[i])!='undefined';vals.push(elements[i++].getAttribute('href'))); 末尾的分号。另一个问题怎么了?
  • @Jákup,我删除了这个问题,因为问题只是因为我错过了将getattribute(val) 更改为getattribute('href')。该语句末尾的分号是正确的,代码运行良好

标签: javascript html jquery-selectors tampermonkey


【解决方案1】:

getElementsByClassName 之后不能使用getElementsByTagName 方法,应该使用:

document.querySelectorAll(".c-card__title > a");

看看this

【讨论】:

  • 对此有更深层次的解释吗?
  • 我给了你文档的链接,但简而言之:它会选择每个具有 .c-card__title 类的元素,他有一个 a 作为孩子
  • @mohamed getElementsByXxxName() 返回一个节点列表。您需要对其进行迭代才能将其与其他搜索方法一起使用。
  • 但是这个方法简化了,因为querySelectorAll()会为你做循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多