Reputation: 13
I have the following DOM structure :
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="main">
<div id="column-1">
This is the column one text
</div>
<div id="column-2">
<div id="part-1">
Part one
</div>
<div id="part-2">
Part two
<script type="text/javascript">
alert($(this).parent().html());
</script>
</div>
<div id="part-3">
Part three
</div>
</div>
</div>
</body>
</html>
What I want is to get the content of the parent (<div id="part-2">
).
The problem is a the instruction : alert($(this).parent().html())
.
Why it is returning null ?
(PS: I know I can reach the <div id="part-2">
with $("#part-2").html()
, but the parent id can change dynamically this is why I want to get that parent with the $(this).parent().html()
instruction)
Upvotes: 1
Views: 1983
Reputation: 13976
The problem is $(this)
doesn't mean anything in a random piece of javascript. You aren't giving it a scope. For example:
$( 'button' ).click( function() { alert( $(this).parent().html() ); } );
In that code, $(this)
refers to the button. You need to bind some event to the div, so that you can use $(this).parent()
;
Another way to think about it is, the placement of the javascript relative to the HTML elements is irrelevant when it comes to objects such as $(this)
;
For your code, you could add this:
$( 'div.column-2 div' ).click( function() { alert( $(this).html() ); } );
That will alert the HTML of the div you click on, and it will work with all three in your example (part-1, part-2 and part-3)
Upvotes: 1
Reputation: 9774
It's returning nil because the DOM is not complete, i.e. when the JS is run the div "part-2" is not closed so it can't get the HTML, never mind the parent HTML, if you put it in a button, then it should work: http://jsfiddle.net/E9eA8/
Upvotes: 0
Reputation: 5553
As i understand you want to show previous sibling and not the parent...try with this:
$("#part-2").prev().html()
Upvotes: 0