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:
<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>
$(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.
HTML. After seeing the result of the above code, it is crystal clear that the ID selector is the fastest.
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . )
The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example).
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 id
property, but a DOM element does. On the other hand, jQuery does provide a way to access elements' properties using the attr
method:
document.getElementById('content').id // access the id property of a DOM element
$('#content').attr('id') // use jQuery to select the element and access the property
The length
property, however, is provided by a jQuery selection, which is why that works fine for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With