how do you get a reference to an outer div using jquery
if i have this html
<div class="whole">This is a <div class="min">Test</div></div>
i want to change the html of the "whole" div when i click on the "min" div:
i have tried this below, but it doesn't seem to work.
$(document).ready(function() {
$('div.min').live('click', function() {
$(this).prev('.whole').html("<img BORDER=0 src='../../images/copy1.png开发者_高级运维' />");
});
});
does anyone have any ideas on whats going wrong here ?
You want parent
, not prev
. Your div.min
is inside, not next to, the div.whole
. So:
$(document).ready(function() {
$('div.min').live('click', function() {
$(this).parent('.whole').html("<img BORDER=0 src='../../images/copy1.png' />");
});
});
2017 update: live
has been deprecated for years and was eventually removed. It's used in the above because it was in the OP's original code and wasn't the issue, but just for completeness, the current way to do this is with on
's delegation signature:
$(document).on('click', 'div.min', function() {
$(this).parent('.whole').html("<img BORDER=0 src='../../images/copy1.png' />");
});
Note that we don't even need the ready
, since this is doing event delegation on document
, so it doesn't have to wait. (That was true of the live
version above as well.)
.prev()
will select the preceding sibling, i.e. the element that precedes the current element at the same level.
You are looking for .parent()
.
E.g.
<div id="parent">
<div id="first"></div>
<div id="second"></div>
</div>
$('#second').prev()
will select#first
.$('#second').parent()
will select#parent
.$('#first').next()
will select#second
.
Another way of doing this would be the follow
$('div.min').click(function(event){
if ($(event.target).is('div.min')){
$('div.whole').html("<img BORDER=0 src='../../images/copy1.png' />");
}
});
精彩评论