How can I find the parent element that loads the children elements without explicitly declaring it from another function?
the jquery,
$(document).ready(function(){
$('.load-child').load_child();
});
(function($) {
$.fn.extend({
load_child: function(options) {
var o = $.extend({
target:'.parent'
}, options);
var $this = this;
var $cm = this.click(function(e) {
var object = $(this);
var path = object.attr('href');
$(o.target).load(path, function(){
$this.child();
});
return false;
});
$this.child = function() {
$('.find-parent').click(function(event){
var object = $(this);
object.parents('.parent').css({background:'red'});
return false;
})
};
return $cm;
}
})
})(jQuery);
index html,
<a href="child.php" class="load-child">load child</a>
<div class="container">
<div class="parent">
</div>
</div>
child page,
<div>
<div></div>
<div></div>
<div><a href="#" class="find-parent">click me</a></div>
</div>
I can get the .parent element above because I declare the parent name explicitly,
object.parents('.parent').css({background:'red'});
But what about if the parent name is unknown or is changed constantly? Is there any generic method to locate/ trace back to the element that is used to load the page?
The loaded page may have loads of div elements, so I can’t do this,
object.parent().css({background:'red'});
or
object.parents(div).css({background:'red'}); // this will go up to the very top of div element.
the jsfiddle page.
Edit:
These are your options:
.closest(".markerName")to find it from anywhere within the content.Note, I think you generally want to be used
.closest(selector)instead of.parents(selector). You can read about it here.Edit – based on the question you ask in your comment:
Storing the load parent in a global variable is my least recommended option, but since you ask how to do it this is how:
When your load-child method does this:
you would just remember the
o.targetvalue like this:Then,
window.loadTargetwill be a global variable containing where you last loaded content.Personally, I would much prefer you use a special class name. So, you’d replace this:
with this:
and then, anywhere inside the content that you want to find the load target, you’d do this:
This second option avoids any new global variables and supports multiple loadTargets at the same time.