itsMe
itsMe

Reputation: 139

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?

<div class="item" id="dessert">
                <div class="item-image-div">
                    <img src="mcd/<?= $row["image"]; ?>" alt="" class="item-image" onclick="getSrc(this.src)">
                </div>
                <div class="item-detail">
                    <div class="item-name" onclick="getSrc(this.name)"><?= $row["item"]; ?></div>
                    <div class="item-order">
                        <div class="item-price"><?= $row["price"]; ?></div>
                        <button class="order">
                            <img src="icon/order.png" alt="" width="40px">
                        </button>
                    </div>
                </div>
            </div>
let orderBtn = document.querySelectorAll('.order');
    orderBtn.forEach(function(btn){
        btn.addEventListener('click', (e)=>{
            if (e.target.parentElement.classList.contains('order')) {
                let fullPath = e.target.parentElement.parentElement.parentElement.previousElementSibling.children[0].src;
                let pos = fullPath.indexOf('mcd') + 3;
                let partPath = fullPath.slice(pos);

                let itemId = e.target.parentElement.parentElement.parentElement.parentElement.id;
                const item = {};
                item.img = `${partPath}`;
                console.log(item);

                let itemName = e.target.parentElement.parentElement.previousElementSibling.textContent;
                let itemPrice = e.target.parentElement.previousElementSibling.textContent;
                console.log(itemName);
                console.log(itemPrice);
            }
        });
    });

Upvotes: 0

Views: 98

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370629

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;
    });
});

Upvotes: 3

Related Questions