Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get id's of all child elements with a particular class

I need to get the id's of the 'vehicle' class from the <ul>. How can I get that using jquery/javascript? Can it be done with iterating through all the elements? Thanks in advance.

<ul id="ulList">
  <li id="car" class="vehicle">
  <li id="bus" class="vehicle">
  <li id="cat" class="animal">
  <li id="dog" class="animal">
  <li id="bike" class="vehicle">
  <li id="monkey" class="animal">
</ul>
like image 522
User_007 Avatar asked Aug 28 '15 12:08

User_007


People also ask

How do I get the div element of all children?

If You want to get list only children elements with id or class, avoiding elements without id/class, You can use document. getElementById('container'). querySelectorAll('[id],[class]'); ... querySelectorAll('[id],[class]') will "grab" only elements with id and/or class.

How do I find the ID of a selected element?

getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

How do I select a specific child in Javascript?

Select the parent element whose child element is going to be selected. Use . querySelector() method on parent. Use the className of the child to select that particular child.


1 Answers

As there are already other answers with jQuery, here is an alternative using vanila Javascript:

var vehicles = document.querySelectorAll("ul#ulList > li.vehicle");
var ids = [].map.call(vehicles, function(elem) {
  return elem.id;  
});
console.log(ids);
<ul id="ulList">
  <li id="car" class="vehicle">
  <li id="bus" class="vehicle">
  <li id="cat" class="animal">
  <li id="dog" class="animal">
  <li id="bike" class="vehicle">
  <li id="monkey" class="animal">
</ul>
like image 113
Abhitalks Avatar answered Oct 07 '22 01:10

Abhitalks