I simply want to manipulate the elements within the #content div, but $('#content') doesn’t seem to work, and yet in other places it does! My relevant code is very simple:
HTML
<body>
<input type='button' value='Save design' id='save' />
<div id="content" style="height: 200px; width:600px;border: 1px solid black;" class='whatev'></div>
</body>
Script
$(document).ready(function(){
$('#save').click(function(e){
alert( document.getElementById('content').id); // this works!
alert($("#content").length); // this works! it outputs "1"
alert($("#content").id); // this does NOT work - undefined, why?
//end save function
});
$('#content').click(function(e){
// do stuff // ALL of this works!
});
});
That is it. If you notice, it does work in some places (the entire click function bound to it is perfectly fine), but where it doesn’t work, it strangely does still exist because length = 1. I tried using context as well to search the div, just in case, (using $('#content','body')), but no use.
There is a difference between a DOM element and a jQuery selection that contains a DOM element. A jQuery selection is a wrapper around the DOM object to make it easier to use. It doesn’t have an
idproperty, but a DOM element does. On the other hand, jQuery does provide a way to access elements’ properties using theattrmethod:The
lengthproperty, however, is provided by a jQuery selection, which is why that works fine for you.