Skip to content

Instantly share code, notes, and snippets.

@luislobo14rap
Last active January 23, 2023 14:12
Show Gist options
  • Save luislobo14rap/5abef4a0559251be25d420df4635e8a8 to your computer and use it in GitHub Desktop.
Save luislobo14rap/5abef4a0559251be25d420df4635e8a8 to your computer and use it in GitHub Desktop.
jQuery.fn.extend({
getParent: function(selector){
if( typeof selector == 'string' ){
//if number in string
if( !!selector.match(/(\d|\.)/g) ){
if( selector.length == selector.match(/(\d|\.)/g).length ){
return $(this).getParent( Number(selector) );
};
};
if( $(selector).is('html') ){
return $('html');
};
let breakWhile = false,
thisParent = $( $(this)[0] );
while( breakWhile == false ){
thisParent = thisParent.parent();
if( thisParent.is('html') ){
return $('html');
};
if( thisParent.is(selector) ){
return thisParent;
breakWhile = true;
};
};
};
let selectorString = (selector).toString();
if( typeof selector == 'number' && !!selectorString.match(/\d/) ){
if( selectorString.match(/\d/).length == selectorString.length ){
let max = selector < 1000 ? 1 : 0;
if( max != 1 ){
return $('html');
};
let thisParent = $( $(this)[0] );
for( let i = -1; i < selector; i++ ){
thisParent = thisParent.parent();
if( thisParent.is('html') ){
return thisParent;
};
};
return thisParent;
};
};
return false;
}
});
"use strict";jQuery.fn.extend({getParent:function(t){if("string"==typeof t){if(t.match(/(\d|\.)/g)&&t.length==t.match(/(\d|\.)/g).length)return $(this).getParent(Number(t));if($(t).is("html"))return $("html");for(var r=!1,e=$($(this)[0]);0==r;){if((e=e.parent()).is("html"))return $("html");if(e.is(t))return e}}if("number"==typeof t&&t.toString().match(/\d/)){if(1!=(t<1e3?1:0))return $("html");for(var n=$($(this)[0]),i=-1;i<t;i++)if((n=n.parent()).is("html"))return n;return n}}});
@luislobo14rap
Copy link
Author

luislobo14rap commented Mar 21, 2018

Example:

$('body').getParent(1); //return $('html') parent
$('body').getParent('html'); //return $('html') parent

//if exist
$('span').getParent('body'); //return $('body') parent

//if exist
$('li').getParent(1); //return $('ul') parent
$('li').getParent('ul'); //return $('ul') parent

//if exist
$('.col-md-12').getParent(1); //return $('.row') parent
$('.col-md-12').getParent(2); //return $('.container') parent

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment