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.
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.
Yes, you can. But note that Id's must be unique within your html file, while classes can be used in multiples elements.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With