How to get the element id from its class

Asked

Viewed 1,909 times

2

I have the following list:

<ul id = "qualquer">
    <li id = "listitem1" class = "middle_item">
    </li>
    <li id = "listitem2">
    </li>
    <li id = "listitem3">
    </li>
</ul>

In my problem, the class = "middle_item" may be in any li, but at this moment, by chance, it lies in the first li.

I created the following javascript, to try to catch the id of li that has the class = "middle_item"

var i = $("#qualquer .middle_item").attr('id').text();
        alert(i);

but the following error is appearing to me:

Uncaught Typeerror: $(...). attr(...). text is not a Function

Any suggestions?

FIDDLE

  • If middle_item has only one element, just do $($('.middle_item')[0]).attr('id');, nay?

  • Do you want to do what? Show the content of li?

  • My fault, I created this example to simplify the original problem. The middle_item has more than one element

  • But you want to catch the id of all the middle_items?

  • @Jeffersonalison I intend to show the id of li

  • @Felipeavelar No. I just want to get the id of the li that has the class middle_item

  • But if several lis may have middle_item, then you will have several ids...

Show 2 more comments

2 answers

4


You can do this only with native Javascript:

var id = document.querySelector('.middle_item').id;

In relation to the error Uncaught TypeError: $(...).attr(...).text is not a function, the problem this error message points to is that when you use .attr('id') this will return a string with a id you want. Try to apply the method .text() to id (string) naturally gives error.

I mean, you can use jQuery: var id = $("#qualquer .middle_item").attr('id'), but only with native Javascript is faster. In case there is no element in the DOM with this class both will give error. jQuery gives But if you do so (as below) will no longer give:

var el = document.querySelector('.middle_item');
var id = el && el.id;

jsFiddle: http://jsfiddle.net/Lrhf958g/

  • 1

    Sergio, one more point to your resume :)

  • @Lollipop thanks :) I like to help notice problems like this.

  • 1

    Just to complement, in your second example there is no error and id will have the value false if the item does not exist.

2

To show only the id of the li that is with the middle_item class:

var i = $("#qualquer .middle_item").attr("id");
alert(i);

Jsfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.