How to get the element id from its class

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, class = "middle_item" can be in any li , but at this point it happens to be in the first li .

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

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

but the following error appears to me:

  

Uncaught TypeError: $ (...). attr (...) text is not a function

Any suggestions?

FIDDLE

    
asked by anonymous 22.05.2015 / 15:22

2 answers

4

You can do this with only native JavaScript:

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

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

That is, 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) it will no longer give:

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

jsFiddle: link

    
22.05.2015 / 15:27
2

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

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

JSFiddle

    
22.05.2015 / 15:28