0
var elem = document.getElementsByClassName("briefsectiontop").querySelector("[data=" + i + "]").getElementsByClassName("current")[0];
if (elem.style.display == "none") {
  elem.style.display = "block";
} else {
  elem.style.display = "none";
};

There are other div elements, but that should be enough to know what the essential HTML looks like, why won't it take my query?

4

1 回答 1

3

如果要搜索的值以数字开头或包含任何非字母数字字符,则必须将其括在引号中:

.querySelector(`[data="${i}"]`)

但是getElementsByClassName返回一个集合,而不是单个元素,所以你不能调用querySelector它。

相反,请考虑仅使用一次调用querySelector

const elm = document.querySelector(`.briefsectiontop [data="${i}"] .current`);

这将选择一个.current具有data您要查找的属性的祖先的元素,该元素也具有一个具有briefsectiontop类名的祖先元素。CSS 选择器允许以非常简洁的方式识别元素。

const i = 3;
const elm = document.querySelector(`.briefsectiontop [data="${i}"] .current`);
console.log(elm);
<div class="briefsectiontop">
  <div data="3">
    <div class="current">
      content
    </div>
  </div>
</div>

于 2019-09-07T23:07:50.063 回答