1

This is my code and i am trying to get values by onclick form a table cells dynamically.

let Table = document.querySelector('#recieve-info');
Table.addEventListener('click',(e)=>{     
     if(e.target && e.target.classList.contains('Save-Button')){
        let tr = document.querySelector('tr');
        console.log(tr.firstElementChild);
    }
});

Here is the output in console.log i am getting only the first value of table cell

1 Answer 1

2

.querySelector() only returns the first matching element.

Use .querySelectorAll(), which will return an array of all matching elements. You'll then have to iterate through the array.

        let trs = document.querySelectorAll('tr'); //**** <- note "All" added
        trs.forEach(tr => console.log(tr.firstElementChild));
Sign up to request clarification or add additional context in comments.

2 Comments

it will always print all values and isn't it better not to search through all document but use e.target instead?
@PaulineNemchak yes, and yes. I'm not saying this is the best way to do things, only explaining why that specific code isn't working. In general I would suggest using React over this style of DOM extraction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.