How to get multiple element id's that have a specific class

I have a bunch of items being created dynamically that a user can select. In which case the class "selected" is added.

<li id="test1" class="myElement selected"></li>
<li id="test2" class="myElement"></li>
<li id="test3" class="myElement"></li>
<li id="test4" class="myElement selected"></li>
<li id="test5" class="myElement selected"></li>
<li id="test6" class="myElement"></li>

How can I get the id's of all the elements that have the "selected" class onclick?

Answers 1

  • Use Document.querySelectorAll() with the selector .selected[id]. That is, all elements with class selected that also have an id attribute.

    const elementsWithSelectedClass = document.querySelectorAll('.selected[id]')
    const selectedElementIds = Array.from(elementsWithSelectedClass) // convert to array
        .map(el => el.id) // map to an array of id values
    
    console.info(selectedElementIds)
    <ul style="list-style:none">
    <li id="test1" class="myElement selected"></li>
    <li id="test2" class="myElement"></li>
    <li id="test3" class="myElement"></li>
    <li id="test4" class="myElement selected"></li>
    <li id="test5" class="myElement selected"></li>
    <li id="test6" class="myElement"></li>
    </ul>

    This will provide you with an array of id values.

    I'm using Array.from to convert the NodeList returned from querySelectorAll to an array so I can use the map method.


Related Articles