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>
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With