querySelector获取class
时间: 2024-02-24 09:52:19 浏览: 134
querySelector是JavaScript中的一个方法,用于通过选择器来获取文档中匹配的第一个元素。可以用于获取具有指定class的元素。
使用querySelector获取class的语法如下:
document.querySelector(".classname");
其中,".classname"是要获取的元素的class名,需要在class名前加上"."作为选择器。
如果有多个元素具有相同的class名,querySelector只会返回匹配的第一个元素。如果要获取所有匹配的元素,可以使用querySelectorAll方法。
以下是一个示例:
HTML代码:
```
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
```
JavaScript代码:
```
var element = document.querySelector(".box");
console.log(element.textContent);
```
输出结果:
```
Box 1
```
相关问题
document.querySelector 获取某个class下级
document.querySelector是JavaScript中的一个方法,用于通过CSS选择器获取文档中匹配的第一个元素。它可以用来获取某个class下的子元素。
使用document.querySelector方法时,需要传入一个CSS选择器作为参数。选择器可以是元素名、类名、ID等等。如果有多个匹配的元素,该方法只会返回第一个匹配的元素。
下面是一个示例代码,演示如何使用document.querySelector获取某个class下的子元素:
HTML代码:
```html
<div class="parent">
<div class="child">子元素1</div>
<div class="child">子元素2</div>
<div class="child">子元素3</div>
</div>
```
JavaScript代码:
```javascript
const parentElement = document.querySelector('.parent');
const childElement = parentElement.querySelector('.child');
console.log(childElement.textContent); // 输出:子元素1
```
在上面的代码中,首先使用document.querySelector('.parent')获取到class为"parent"的父元素,然后使用parentElement.querySelector('.child')获取到class为"child"的子元素。最后,通过childElement.textContent可以获取到子元素的文本内容。
怎么用querySelector获取input里面的name
你可以使用以下代码来获取input元素中的name属性:
```
const input = document.querySelector('input');
const name = input.getAttribute('name');
console.log(name);
```
这里使用了`querySelector`方法来获取第一个input元素,然后使用`getAttribute`方法获取name属性的值,并将其存储在一个变量中。最后,我们使用`console.log`输出这个变量的值。如果有多个input元素,你可以使用其他选择器来获取你想要的那个input元素,例如通过id、class等属性。
阅读全文
相关推荐















