Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the id of elements with same class

Tags:

html

jquery

How to get each attr id for elements that have the same class?

var id = $('.class').attr('id');

But when I do a console.log it only returns one id even though I have more than one id and multiple divs with same classes.

like image 510
Ionut Avatar asked Aug 06 '15 09:08

Ionut


People also ask

How do you get all elements with the same class?

We can get text from multiple elements with the same class in Selenium webdriver. We have to use find_elements_by_xpath(), find_elements_by_class_name() or find_elements_by_css_selector() method which returns a list of all matching elements.

Can an element have the same ID and class?

Yes, you can. But note that Id's must be unique within your html file, while classes can be used in multiples elements.

How do I find an element with a specific ID?

Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

Can you get multiple elements by ID?

The id must be unique. There can be only one element in the document with the given id . If there are multiple elements with the same id , then the behavior of methods that use it is unpredictable, e.g. document. getElementById may return any of such elements at random.


1 Answers

Use map()

var ids = $('.class').map(function() {
  return $(this).attr('id');
});
console.log(ids);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="class" id="1"></div>
<div class="class" id="2"></div>
<div class="class" id="3"></div>
like image 183
AmmarCSE Avatar answered Oct 15 '22 12:10

AmmarCSE