How to get parent id by name of one class in jQuery?

<div id=id1>
<input class=class1>
</div>

<div id=id2>
<input class=class1>
</div>

Above my html tags. in the code below, I selected a parent id like this,

$(".class1").parent().attr('id')

but i only get id1. I want both id1 and id2. ?? what to do?

+4
source share
4 answers

in accordance with the documents:

.attr (attributeName): Get the attribute value for the first element in the set of matched elements.

Thus, you need to use a function .map()to get the identifier of all elements together with .get()to get them in an array:

$(".class1").parent().map(function(){
    return this.id;
}).get();

Working demo

+5
source

try it

$(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>
Run codeHide result
+2

, parent()

.map(), .class1

var arr = $('.class1').map(function(){
    return this.parentNode.id    
}).get();
alert(arr)

+1
source

The $ .map () method applies a function to each element in an array or object and maps the results to a new array.

 $(".class1").parent().map(function() {
        return this.id;
      })
      .get()
      .join();

This will return "id1, id2".

In the callback function, this refers to the current DOM element for each iteration. A function can return a single data item or an array of data items that need to be inserted into the result set. If the array is returned, elements inside the array are inserted into the set. If the function returns null or undefined, the element will not be inserted.

+1
source

Source: https://habr.com/ru/post/1584832/


All Articles