Skip to content Skip to sidebar Skip to footer

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 <

Solution 1:

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.

Solution 2:

id is a plain DOM property/attribute, and works with plain DOM objects, not jQuery objects.

You would do this in jQuery:

$("#content").attr('id');

which equals:

document.getElementById('content').id

or

$("#content")[0].id; //[0] gets the first DOM object in the collection

Solution 3:

Try this

$("#content").attr("id")

Solution 4:

$("#content") returns the jQuery collection containing the elmenent with id content. id is an attribute of an element, not a property of the collection. You would get the element's ID by chaining the attr() method off the collection:

alert($("#content").attr('id'));

Or, when eaching the collection, inside the function passed to eachthis will be the actual element, so you could access this.id

$("#content").each(function () {alert(this.id);});

Solution 5:

For this question you should go straight to jsfiddle, and to the jquery docs for how to get attributes of html elements -> http://api.jquery.com/attr/.

The jQuery selector object itself doesn't have an attribute id. You have to use .attr('id') function.

I fixed that and everything else works, as you see in this jsfiddle: http://jsfiddle.net/AdtrX/1/

Post a Comment for "Jquery Selector Intermittent Working, Why?"