Find a Javascript parent node that matches a certain string
230
post-template-default,single,single-post,postid-230,single-format-standard,bridge-core-3.0.1,qodef-qi--touch,qi-addons-for-elementor-1.5.3,qode-page-transition-enabled,ajax_updown,page_not_loaded,,vertical_menu_enabled,no_animation_on_touch,side_area_uncovered_from_content,qode-theme-ver-28.7,qode-theme-bridge,disabled_footer_top,qode_header_in_grid,wpb-js-composer js-comp-ver-6.8.0,vc_responsive,elementor-default,elementor-kit-6

Find a Javascript parent node that matches a certain string

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



Mastodon