what's the difference between .id and .attr('id') in jquery
题
var x = $(this).parent().parent().parent().parent();
x.id
gives me undefined
while x.attr('id')
returns the correct id.
Can anyone tell me the difference between those two.
btw, is there a better way to get $(this).parent().parent().parent().parent()
, I don't want to assign ids to them since this would make it harder to work with those elements.
Thanks
解决方案
x.id
works when x
is a DOM element, not when x
is a jQuery object.
If x
is a jQuery object, you can either do:
x[0].id
to get the first DOM element from the jQuery object or you can use:
x.attr('id')
to use the jQuery method for retrieving an attribute.
As for your other question, the better way to replace this:
$(this).parent().parent().parent().parent()
is to put a class on the desired parent and use this:
$(this).closest(".target")
The .closest(selector)
method will find the nearest parent that matches the selector. Using a class to solve this issue makes it easy to design since you don't have to use unique IDs.
其他提示
.id is a property of the dom element whereas your code is fetching a jquery object. See this example. Oh, and note that if you are in jQuery 1.7+ you probably want to be using prop
and not attr
$('#foo').prop('id'); //foo
$('#foo').id; //undefined
$('#foo').get(0).id; //foo
If possible, I would try and define classes to represent your quadruple parent element. Then you could do something like
$(this).parents('.class');
Note the use of parents with an 's'
$(this).parent().parent().parent().parent()
can be written as:
$(this).parents().eq(3)
or:
$(this).parents(':eq(3)')