JavaScript
Article
By Adam Roberts

Access a Parent Element With JavaScript or jQuery

By Adam Roberts
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

Often you’ll want your JavaScript functions to access parent elements in the DOM.

To accomplish this in JavaScript, try element.parentNode.

To do the same in jQuery, try element.parent().

--ADVERTISEMENT--

Here’s a JavaScript example.

HTML:

<ul id="tabs">
<li class="firsttab"><a href="#">one</a></li>
<li class="secondtab"><a href="#">two</a></li>
</ul>

JavaScript:

function init() {
  var tablinks = document.getElementById('tabs').getElementsByTagName('a');
  for (var i = 0, j = tablinks.length; i < j; i++) {
    tablinks[i].onclick = doit;
  }
}
function doit() {
  alert(this.parentNode.className);
}
window.onload = init;
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?