Find a Javascript parent node that matches a certain string

by Thomas Beutel

Here’s a small bit of javascript that I use in my Sencha Touch projects to find a parent with an id that matches a string.


function findParentNodeRegex(regex, childObj) {
var testObj = childObj;
var count = 1;
while(!testObj.id.match(regex)) {
//console.log('My name is ' + testObj.id + '. Let\'s try moving up one level to see what we get.');
testObj = testObj.parentNode;
count++;
}
// now you have the object you are looking for - do something with it
//console.log('Finally found ' + testObj.id + ' after going up ' + count + ' level(s) through the DOM tree');
return testObj;
}

Suppose that you tapped an paragraph element that was nested like so and “target” points to the paragraph:

<div id="news1234"><div class="content"><p>Tap me!<p></div></div>

You can find the parent that matches the string “news” like so:

var newsParent = findParentNodeRegex(/news/,target);
console.log("Id is "+newsParent.id); // prints "Id is news1234"

I adapted the code from here