最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the parent div id from the anchor child - Stack Overflow

programmeradmin2浏览0评论
<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
  • 9 alert(this.parentNode.id) – R Lam Commented May 5, 2015 at 7:34
Add a comment  | 

4 Answers 4

Reset to default 14

Use 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>
发布评论

评论列表(0)

  1. 暂无评论