简体   繁体   中英

Javascript: How to get only one element by class name?

How do I get only one DOM element by class name? I am guessing that the syntax of getting elements by class name is getElementsByClassName , but I am not sure how many elements it's going to return.

document.getElementsByClassName('className') would always return multiple elements because conceptually Classes are meant to be applied to multiple elements. If you want only the first element in the DOM with that class, you can select the first element out of the array returned.

var elements = document.getElementsByClassName('className');
var requiredElement = elements[0];

Else, if you really want to select only one element. Then you need to use 'id' as conceptually it is used as an identifier for unique elements in a Web Page.

// HTML
<div id="myElement"></div>

// JS
var requiredElement = document.getElementById('myElement');

Clarifications :

  1. getElementsByClassName returns a Node List and not an array

  2. You do not need jQuery

  3. What you were looking for was probably document.querySelector :

How do I get only one DOM element by class name?

var firstElementWithClass = document.querySelector('.myclass');

Also see: https://developer.mozilla.org/en/docs/Web/API/Document/querySelector

You can use jQuery:

$('.className').eq(index)

Or you can use the javascript built-in method:

var elements = document.getElementsByClassName('className');

This returns a nodeList of elements that you can iterate and make what you want.

If you want only one, you can access the elements in the javascript version like this:

elements[index]

致任何正在寻找单衬里的人

var first = getElementsByClassName('test')[0];

您可以使用querySelector执行以下操作

var firstElementWithClass = document.querySelector('.myclass');

Use NodeList.item() .

For example:

var first = getElementsByClassName('test').item(0);

You can try with this:

document.getElementsByClassName("className")[index]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM