Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector intermittent working, why?

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.

like image 597
user961627 Avatar asked Aug 28 '12 11:08

user961627


People also ask

Which jQuery selector is fastest?

HTML. After seeing the result of the above code, it is crystal clear that the ID selector is the fastest.

How do jQuery selectors work?

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.

Are jQuery selectors the same as CSS 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 ( . )

What does jQuery selector return?

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).


1 Answers

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.

like image 174
lonesomeday Avatar answered Sep 30 '22 12:09

lonesomeday