• Skip to content

Menu 1

  • Zug
  • Blog
  • Local
  • Printed
  • Projects
  • Railroad
  • Podcasts
  • Newsletter

Thomas Beutel Art

Menu 1

  • Zug
  • Blog
  • Local
  • Printed
  • Projects
  • Railroad
  • Podcasts
  • Newsletter

Follow us

Follow us on TwitterFollow us on InstagramFollow us on PinterestSubscribe to our Channel on YouTubeFollow us on SoundCloud
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

© 2025MINIMAL

Follow us

Follow us on TwitterFollow us on InstagramFollow us on PinterestSubscribe to our Channel on YouTubeFollow us on SoundCloud
x