Access a Parent Element With JavaScript or jQuery

Tweet

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

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;

Learn HTML5 Online

Get all SitePoint books and courses with a Learnable membership. Start building future-proof websites that are faster, more powerful, and easier to maintain.

No Reader comments