TL;DR
[HTML-Node-Attribute="值"]
属性选择器
HTML-Element-Attributes id 和 class 确实有自己的 css-selecoring:
其他属性确实需要其他东西。比如“属性选择器”。
例如,您有以下类似的 HTML 代码:
<a href="#top">Go to top!</a>
使用属性选择器,您可以获取此元素,并具有以下所有可能性:
[href] /*looking only for the attribut. No matter what value is inside*/
[href="#top"] /*the attributes value must be "#top"*/
a[href="#top"] /*the same as the example above but in this case href needs to be a attribute of "a"-tag*/
有一些更酷的可能性来处理一个元素。更多信息见MDN Attribute selectors
querySelector / querySelectorAll
querySelector 为您提供等于传递的第一个元素
CSS 选择器。
好的,我想这可能更容易通过示例而不是文字墙来理解。那么让我们开始吧:
对于这个例子,我将使用这个 HTML 片段:
<div class="container">
<div data-id='cat'>
<button name='cat' value='miau'>Cat</button>
</div>
<div data-id='dog'>
<button name='dog' value='not miau'>Dog</button>
</div>
</div>
当您询问如何通过 querySelector 的名称查找元素时,我将从以下内容开始:
有两个具有名称属性的元素。两者都是按钮,但名称不同。
要获取具有 name 属性的第一个元素,请使用:
document.querySelector('[name]') //get button cat because it's the first one in the dom (in that example)
要让他们都试试这个:
document.querySelectorAll('[name]') //get both buttons (cat, dog)
当你知道你要找的名字时
document.querySelector('[name="cat"]') //get the first element where name equals 'cat'
与数据、类或 id 等其他属性相同
document.querySelector('[data-id="cat"]') //get div
您还可以一次执行多个 dom 步骤:
document.querySelector('[data-id="cat"] button') //gets the first button inside "cat-div"
文档
请参阅MDN 和Microsoft 了解更多信息。
您可能也对CSS-Selectors 感兴趣。