<div class="wizard-rules" id="wizard-rule">If <a href="#" onclick="alert(this.id)" id="dashboard-rule-2" class="highlight">ALL DASHBOARD</a> encounters an error</div>
Here i want to get the div id wizard-rule
onclick on the anchor tag. how can i do that?
the anchor tag now is just getting the id of the anchor tag itself. but not the id of its parent element.
<div class="wizard-rules" id="wizard-rule">If <a href="#" onclick="alert(this.id)" id="dashboard-rule-2" class="highlight">ALL DASHBOARD</a> encounters an error</div>
Here i want to get the div id wizard-rule
onclick on the anchor tag. how can i do that?
the anchor tag now is just getting the id of the anchor tag itself. but not the id of its parent element.
Share Improve this question asked May 5, 2015 at 7:30 CeejayCeejay 7,26719 gold badges65 silver badges109 bronze badges 1 |4 Answers
Reset to default 14Use parentNode
to access on your id
<div class="wizard-rules" id="wizard-rule">If <a href="#" onclick="alert(this.parentNode.id)" id="dashboard-rule-2" class="highlight">ALL DASHBOARD</a> encounters an error</div>
You can get parent ID like this:
window.onload = function(){
var element = document.getElementById('child').parentNode;
alert(element.id);
}
Or you can use JQuery to do that:
var id = $('child').parent().prop('id');
1st method:
The parent()
method traverses to the immediate parent of each of the element in the DOM tree. Parent()
travels a single level up the DOM.
$('a').click(function(){
alert($(this).parent().prop("id"));
});
and remove the onclick
from the Anchor tag in the HTML
2nd Method:
The parentNode
property returns the parent node of the specified node, as a Node object.
In your HTML add this.parentNode.id
to onclick
event of anchor
element:
<a href="#" onclick="alert(this.parentNode.id)" id="dashboard-rule-2" class="highlight">ALL DASHBOARD</a>
Please try this will work fine :
<div class="wizard-rules" id="wizard-rule">If <a href="#" onclick="alert($(this).parent().attr('id'))" id="dashboard-rule-2" class="highlight">ALL DASHBOARD</a> encounters an error</div>
alert(this.parentNode.id)
– R Lam Commented May 5, 2015 at 7:34