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)
The problem is
$(this)doesn’t mean anything in a random piece of javascript. You aren’t giving it a scope. For example: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:
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)