开发者

How to find the id of an element using jQuery

开发者 https://www.devze.com 2023-02-13 11:46 出处:网络
This is the html code < body > < div id=\"map\" > I am traversing 开发者_开发百科the parents until I find the body to find the map

This is the html code

  < body >    
     < div id="map" >

I am traversing 开发者_开发百科the parents until I find the body to find the map

var pageFrom= $(theElement).parentsUntil( 'body' );    
var pageFromId = $(pageFrom).attr("id"); 

in firebug i see pageFrom [div#map.current]

The problem is that pageFromId is "" and it should be "map"


If you're using the parentsUntil()[docs] method, it is retuning a collection of ancestors ordered from those nearest the starting point to those farthest away.

Because of this, you'll need to access the last one in the collection to get its ID.

var pageFrom= $(theElement).parentsUntil( 'body' );
var pageFromId = pageFrom.last().attr('id');

or

var pageFrom= $(theElement).parentsUntil( 'body' );
var pageFromId = pageFrom.slice(-1).attr('id');

Note that you can also grab the ID as a property on the element:

var pageFromId = pageFrom.get(-1).id;


try this:

$(theElement).closest( 'map' );
or
$(theElement).closest( 'body' ).attr('id'); 


Maybe

pageFrom.first().attr("id")

?

But you should be more specific about what you need. Do you really need all the parents between the element and body? Otherwise, you can use .closest.

Also, in your inital code, you don't need to use $(pageFrom) since it's already a jquery object.


I'm not quite sure what you're asking here. But if the pattern here is that the first <div> after the <body> has an ID, and that's what you're trying to grab, something as simple as this should do the trick:

$('body').find('div:first').attr('id');

There's no reason to traverse upward to the document's body -- there should always be one, so why not start there and work down?


From the docs:

Given a jQuery object that represents a set of DOM elements, the .parentsUntil() method traverses through the ancestors of these elements until it reaches an element matched by the selector passed in the method's argument. The resulting jQuery object contains all of the ancestors up to but not including the one matched by the .parentsUntil() selector.

That means you're attempting to call attr on an array of elements, not the final element itself. What exactly is it that you want to do? Do you want to find the first element within the body, or do you want to find the closest element that matches a selector?

// find first element of a type
$('div:first').attr('id')

// find closest element of a type
$(this).closest('div').attr('id')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号