Skip to main content

Access a Parent Element With JavaScript or jQuery

By Adam Roberts

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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;

Adam is SitePoint's head of newsletters, who mainly writes Versioning, a daily newsletter covering everything new and interesting in the world of web development. He has a beard and will talk to you about beer and Star Wars, if you let him.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.