parentElementsByTagName(doc, tagname, classname)

06 March 2006   3 comments   Web development

Mind That Age!

This blog post is 11 years old! Most likely, its content is outdated. Especially if it's technical.

Powered by Fusion×

I've just written a little javascript function that I have myself found extremely valuable when doing DOM scripting. It's called parentElementsByTagName() and even if it's name isn't great it really does work and has proven very useful for my app.

At any starting point in a DOM tree (first parameter) it goes "up the tree" by looping over "currentelement.parentNode". The second parameter is the tag name (eg. "div") and the third parameter is optional and it's a class name that that tag name needs to have.

I wrote this because I found myself writing this.parentNode.parentNode.parentNode... in my Javscript code and thought I'd stop that sillyness.

Here's my code. I'm sure it ain't perfect but it's helped me a lot and maybe it will help others:

/* This function returns a list of elements that are all parents of each
* other and parent of 'doc'. They're matched by tagname and *optionally*
* classname. */
function parentElementsByTagName(doc, tagname, classname) {
  var findings = new Array();
  var digg_in = doc;
  while (digg_in.parentNode) {
     digg_in = digg_in.parentNode;
     if (digg_in.nodeName.toLowerCase() == tagname.toLowerCase()) {
        if (arguments.length==3) {
           if (digg_in.getAttribute('class') &&
               digg_in.getAttribute('class').toLowerCase().indexOf(classname.toLowerCase())>-1) {
              findings.push(digg_in);
           }
        } else {
           // no doubt
           findings.push(digg_in);
        }
     }
  }
  return findings;
}

Comments

Matt Schinckel
I wrote a similar function, but mine was to find the parent form:

function parentForm(node) {
if (node==document) return false;
if (node.tagName=="FORM") return node;
return parentForm(node.parentNode);
}

I kinda like it, as it's very simple - and uses recursion to make it even simpler. I don't know if there's a limit in JavaScript to the number of stack that can be recursed.
Neville Shaun Ng
getAttribute("class") doesn't work in IE btw
Neville Shaun Ng
.className needs to be used instead for IE
Thank you for posting a comment

Your email will never ever be published


Related posts

Previous:
tightVNC and Chicken of the VNC 04 March 2006
Next:
Squeezebox + Pandora 08 March 2006
Related by Keyword:
V8 < TraceMonkey < SquirrelFish 23 September 2008
Lesson learnt with creating DOM element with jQuery 04 April 2008
Are you a web developer? Then VisiBone is for you 22 January 2006
DOM Scripting 05 December 2005
Related by Text:
Careful when dealing with options in IE 14 April 2006
QUnit testing my jQuery Mobile site in full swing 17 March 2011
US License Plate Spotter (part 2) 08 August 2012
Don't that this or bind 12 April 2016
What stumped me about AngularJS 12 May 2013