1

i have to remove buttons here and i can't access them each, i tried all still the same. The HTML CODE

<div class="grocery_list_items">

                    <div class="grocery_items">
                        <div class="count">1.</div>
                        <div class="item_name">Short Wears</div>
                        <div class="remove_item_button" id="remove_btn">Remove</div>
                    </div>
                    <div class="grocery_items">
                        <div class="count">1.</div>
                        <div class="item_name">Short Wears</div>
                        <div class="remove_item_button" id="remove_btn">Remove</div>
                    </div>
                </div>

AND the javascript code to access the buttons

let remove_button = document.getElementById("remove_btn");
console.log(remove_button)

the console is only showing a result for one button instead of two, how do i solve this?

  • 4
    `id` should be unique, use class names if you need the same identity for different elements. See [How to remove all elements of a certain class from the DOM?](https://stackoverflow.com/questions/10842471/how-to-remove-all-elements-of-a-certain-class-from-the-dom) – Alex K. Jul 13 '22 at 13:12
  • if you want all `remove` button then use `getElementByClassName` . – Mohit Sharma Jul 13 '22 at 13:14
  • @MohitSharma worked perfectly, but how do i know when to use ```getElementByClassName```? – dynamitetech Jul 13 '22 at 13:17
  • To be clear, it's `getElement**s**ByClassName()` and you would use it when you want to get a group of elements by their class name. Classes group elements; ids are unique. Another more flexible option would be `document.querySelectorAll(#idSelector, .classSelector)` – mykaf Jul 13 '22 at 13:24
  • @dynamitetech its depend on your requirement that what you want, for this you have to read js dom manupilation and access doc, just search for it. – Mohit Sharma Jul 13 '22 at 16:17

0 Answers0