pb_
pb_

Reputation: 492

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 "search_results" with javascript?

Upvotes: 2

Views: 1422

Answers (5)

spikeheap
spikeheap

Reputation: 3887

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];

Upvotes: 0

hungryMind
hungryMind

Reputation: 6999

If you use JQuery $(".search_results").first(). Else you need to use document.getElementsByClassName("search_results")[0];

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163268

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];

Upvotes: 1

danpickett
danpickett

Reputation: 2046

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

Upvotes: 0

James Allardice
James Allardice

Reputation: 165991

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.

Upvotes: 1

Related Questions