• Skip to content

Menu 1

  • Home
  • Work
  • Small Worlds
  • Play
  • Blog
  • Podcasts
  • Newsletter
  • About

Thomas
Beutel

Kinetic sculpture · prints · small worlds · stories
  • Home
  • Work
  • Small Worlds
  • Play
  • Blog
  • Podcasts
  • Newsletter
  • About
AuthorPostedbyThomason May 20, 2011

Find a Javascript parent node that matches a certain string

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

♡

Posted in javascript, Programming

Post navigation

Previous
Next
© 2026 Thomas Beutel Instagram · YouTube · SoundCloud
x