Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Get All Parent Id's By Same Class Name In Jquery?

Tags:

html

jquery

<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 ?

like image 764
Vicky Siddharth Avatar asked Jan 08 '23 12:01

Vicky Siddharth


2 Answers

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();

Working Demo

like image 108
Milind Anantwar Avatar answered Jan 11 '23 03:01

Milind Anantwar


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>
like image 28
Anik Islam Abhi Avatar answered Jan 11 '23 03:01

Anik Islam Abhi