简体   繁体   中英

How to get the parent div id from the anchor child

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

使用parentNode访问您的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>

请尝试这将工作正常:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM