首页 > 解决方案 > HTML选择没有类的特定元素

问题描述

正如标题所说,我不知道如何只选择第一个h1“我要选择这个”

特别是不使用类,只使用 HTML 文本中的第一个 h1

标签: htmlcss

解决方案


非常简单的querySelector就可以了

// first h1 in header

console.log(
  document.querySelector("header > h1").textContent
)

// first h1 in document:

console.log(
  document.querySelector("h1").textContent
)
header > h1 {
  color: green
}
<header>
  <h1>I want to select this</h1>
  <div>
    <h1>Welcome to the world!</h1>
    <p>I don't like apples</p>
  </div>
</header>


推荐阅读