gabaum10
gabaum10

Reputation: 3827

Javascript - extract object ID from a Javascript object

So I am not sure if my title is clear enough. I essentially have a div saved as a Javascript object which looks like this: [div#field_30.checkbox_group]

The field_30 is the ID which I am trying to extract here. doing something like object.id is not working. Does anyone know how to get the ID?

Note: I saved the object like this: var object = $(".workspace .selected"); which grabs the currently selected div inside the object called workspace. Sorry is this is a rookie mistake, I just can't seem to find anything anywhere. Thanks for the help...

Upvotes: 0

Views: 2943

Answers (5)

przemoc
przemoc

Reputation: 3869

I don't see a complete answer here, so I'll provide my own.

If you're using jQuery selector $(), then you'll get jQuery-wrapped collection, not a single element.

(I assume now that you're using jQuery 1.5.2, the same as StackOverflow uses now.)

  • Universal solution to get ids of all elements returned by selector is:

    .map(function(){ return this.id; })
    

    Running $(".post-text").map(function(){ return this.id; }) on current page will return something like: ["", "", "", "", ""]

  • To get id of the first element returned by selector use:

    .attr('id')
    

    Running $("div").attr('id') on current page will return "notify-container".

    Since jQuery 1.6 you can also use .prop('id') here.

If you know, that query will return only one element or you just want the first element matching given selector, then use .attr which is obviously a simpler solution.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754575

In this case it looks like object is the result of a jQuery select. To get to the actual DOM object you need to use [0]. Then you can access the id property

object[0].id

Upvotes: 0

Lepidosteus
Lepidosteus

Reputation: 12027

You can use either $jquery_object.attr('id') or $jquery_object.eq(0).id

See this for exemple: http://jsfiddle.net/cquuT/

Upvotes: 0

Andrew
Andrew

Reputation: 13853

Your object is in fact a jQuery object, not a dom object.

To use the dom object use,

object[0].id

Or using, jquery, (Since it is already there)

object.prop('id'); 

Upvotes: 0

Andy E
Andy E

Reputation: 344527

var object = $(".workspace .selected"); will return a jQuery wrapped element that has jQuery properties and methods rather than element properties and methods. This means that any of

object[0].id
object.prop("id")
object.attr("id")

should work, but the 1st option should be the best performance-wise. It gets the id property of the the 1st element contained by the jQuery object, which is your div.

Upvotes: 2

Related Questions