Reputation: 127
<div id=id1>
<input class=class1>
</div>
<div id=id2>
<input class=class1>
</div>
Above is my html tags. in below code i have select the parent id like this,
$(".class1").parent().attr('id')
but i am getting id1 only .i want both id1 and id2. ?? what to do ?
Upvotes: 4
Views: 1884
Reputation: 1902
The $.map() method applies a function to each item in an array or object and maps the results into a new array.
$(".class1").parent().map(function() {
return this.id;
})
.get()
.join();
This will return "id1, id2".
Within the callback function, this refers to the current DOM element for each iteration. The function can return an individual data item or an array of data items to be inserted into the resulting set. If an array is returned, the elements inside the array are inserted into the set. If the function returns null or undefined, no element will be inserted.
Upvotes: 1
Reputation: 20636
Your code got Id attribute of just the first element of the result obtained by parent()
Use .map()
to traverse through .class1
var arr = $('.class1').map(function(){
return this.parentNode.id
}).get();
alert(arr)
Upvotes: 1
Reputation: 25352
Try like this
$(function(){
$(".class1").each(function(){
var id = $(this).parent().attr("id");
console.log(id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1">
<input class="class1">
</div>
<div id="id2">
<input class="class1">
</div>
Upvotes: 2
Reputation: 82241
as per docs:
.attr( attributeName ): Get the value of an attribute for the first element in the set of matched elements.
Thus, you need to use .map()
function to get all elements id along with .get()
to get them in array:
$(".class1").parent().map(function(){
return this.id;
}).get();
Upvotes: 5