从JQuery中的父元素中选择一个ID

从JQuery中的父元素中选择一个ID

问题描述:

I want to access the id of the parent element. This code I am using and it's not working

var tag_id= $('.tag').closest('.tag').attr('id');
alert(tag_id)

This is my html

<div class='tag' id='<?php echo "$id";?>'>
   <span class='tagName' id='<?php echo "$tag_name";?>'>Something</span>
</div>

I am not using .click() or .hover()

Probably the html div is in a while loop so 10 records will come from the database and it shows the same id for all records

EDIT:

I have another var but I didn't include this is it:

var tag_name = $('.tag').children('.tagName').attr('id');

its the name of the tag even though it's coming same for all tags

I tried the code from the answer for the second one and it didn't work

Html:

<div class='tag' id="<?php echo $id;?>">
   <span class='tagName' id="<?php echo $tag_name;?>">Something</span>
</div>

Jquery

$('.tag').find('.tagName').attr('id'); // get child id

$('.tag').attr('id'); // parent id

Try this :

var tag_id= $('.tag').attr('id');
alert(tag_id)