access divs of same class name using javascript
I have the following html code-
<div class="search_results">...</div>
<div class="search_results">...</div>
<div class="search_results">...</div>
The divs are automatically generated by a javasciprt function. Is there a way to access only the first div/or a specific div of the same class name "sea开发者_StackOverflow中文版rch_results" with javascript?
If you use JQuery $(".search_results").first()
. Else you need to use document.getElementsByClassName("search_results")[0];
You can use getElementsByClassName
which returns a NodeList (which is an array-like object). You can then access individual elements of that using normal array syntax. This example will return the first element:
var firstDiv = document.getElementsByClassName("search_results")[0];
Or, you could use querySelector
, which returns the first element found:
var firstDiv = document.querySelector(".search_results");
If you want to return all matched elements, you can use querySelectorAll
, which returns a NodeList, like getElementsByClassName
.
Use getElementsByClassName
or querySelector
(if available):
function findElementsByTagNameAndClassName(tag, class_name) {
if(typeof document.querySelector !== 'undefined') {
return document.querySelector(tag + ' .' + class_name);
}
var els = document.getElementsByClassName(class_name);
var result = [];
for(var i = 0; i < els.length; ++i) {
if(els[i].nodeName === tag) {
result.push(els[i]);
}
}
return result;
}
var firstDiv = findElementsByTagNameAndClassName('div', 'search_results')[0];
If you're using JQuery:
$("div.search_results").first() for later versions of JQuery and $("div.search_results")[0] for older ones.
No Jquery: document.getElementsByClassName
If you want to access a specific instance, you will want to add an id attribute to the elements, for example:
<div class="search_results" id="result_1">...</div>
<div class="search_results" id="result_2">...</div>
<div class="search_results" id="result_3">...</div>
If that's not an option, you can access the n'th item with the classname (starting from 0) using
var divN = document.getElementsByClassName("search_results")[n];
精彩评论