Skip to content Skip to sidebar Skip to footer

Better Way To Get Dom Element

I want to get a specific element when the button clicked. I select the clicked data with DOM Traversal method, Is there any method I can use to get an element faster?

Solution 1:

Instead of adding a listener to the button and checking inside the handler that the clicked parent is the .order, add a listener to the <img> instead. (Or, is that even needed? Could you permit clicks on both the <img> and the outer <button>, maybe? That'd make more sense to me, if possible)

Utilize .closest to avoid having to use lots of difficult-to-read .parentElement accesses.

Use querySelector to readably navigate down to descendants of the whole .item.

document.querySelectorAll('.order > img').forEach((img) => {
    img.addEventListener('click', () => {
        const item = img.closest('.item');
        const fullPath = item.querySelector('img').src;
        const pos = fullPath.indexOf('mcd') + 3;
        const partPath = fullPath.slice(pos);
        const itemId = item.id;
        const itemName = item.querySelector('.item-name').textContent;
        const itemPrice = item.querySelector('.item-price').textContent;
    });
});

Post a Comment for "Better Way To Get Dom Element"