justin
justin

Reputation: 1699

Getting an element's `id` attribute

Can you get the id attribute of a html tag using jQuery or without?

For example:

<ul id="todo" />

How can I get the id, without using jQuery("#todo")?

Is there a way for that? Will attr() work?

Upvotes: 4

Views: 39538

Answers (5)

robiulhr
robiulhr

Reputation: 51

This can be an option

document.getElementsByTagName('ul')[0].id

Also the attributes property can help:

const list = document.querySelector("ul");
console.log(list.attributes.id)

Upvotes: 1

  vrnvorona
vrnvorona

Reputation: 476

$('.class')[0].id or $('.class').get(0).id

If you need this for multiple elements do

$('.class').each(function() {
    this.id
}

You can also use conventional .attr but it's slower. Though difference is not major, I don't see any drawbacks and syntax is basically same, unless you need to chain-edit attributes.

Upvotes: 1

Geoff
Geoff

Reputation: 9340

Yes, you can use .attr('id') to get the id of an element

Upvotes: 0

John Gathogo
John Gathogo

Reputation: 4655

The way I see it, you most probably need to attach a selector class to the ul so that you can use it to get the id:

<ul id="todo" class="todoclassname" />

then, you can get the id by doing:

$(".todoclassname").attr("id");

Upvotes: 4

alex
alex

Reputation: 490153

You can use attr('id') in jQuery or the id property (or getAttribute('id')) on the native DOM element.

Upvotes: 12

Related Questions