Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get id of parent element of currently clicked element in AngularJS

Tags:

angularjs

How do I get the id of a parent element of currently clicked element in AngularJS?

<div id="d8" class="menutitles ng-scope" ng-repeat="title in list">
     <div class="right" ng-click="showsubmenu($event)">+</div>
     <div class="left" ng-click="showsubmenu($event)">Unit 9</div>
</div>

How to get the value d8 in showsubmenu($event) function?

Below is what I tried but it doesn't work

$scope.showsubmenu=function(obj)
{
    alert(obj.target.parent.attributes.id)
}
like image 492
bharath Avatar asked Sep 09 '14 09:09

bharath


People also ask

How do I get the ID of a clicked element?

To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.

How do I know which ID is clicked in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.


2 Answers

It should be parentNode, not just parent:

alert(obj.target.parentNode.id);

Also attributes is redundant as you can access id property directly.

But note, that since you have ngRepeat, it will create invalid markup, since ids are going to be duplicated. You probably want to fix this too, maybe like this or use classes:

<div id="d8{{$index}}" class="menutitles ng-scope" ng-repeat="title in list">
    <div class="right" ng-click="showsubmenu()">+</div>
   <div class="left" ng-click="showsubmenu()">Unit 9</div>
</div>
like image 57
dfsq Avatar answered Oct 14 '22 11:10

dfsq


<div id="d8" class="menutitles ng-scope" ng-repeat="title in list">
    <div class="right" ng-click="showsubmenu()">+</div>
   <div class="left" ng-click="showsubmenu()">Unit 9</div>
</div>

It should be enough :D

function showsubmenu($event){
    $($event.target).parent();

}

Have a nice day

like image 21
Pedro Augusto Freitas de Souza Avatar answered Oct 14 '22 11:10

Pedro Augusto Freitas de Souza