1

Here is the HTML:

<ul class="drum">
 <li>A</li>
 <li>S</li>
 <li>D</li>
</ul>

Here is the JS:

const Olist = document.querySelectorAll('.drum li');
  for(let i = 0; i < Olist.length; i++){
    Olist[i].addEventListener('click', function(e){
        console.log(`I was clicked ${Olist[i]}`);
    })
 }

My console.log() inside the loop returns the following: I was clicked [object HTMLLIElement] I don't understand why am I getting [HTMLLIElement] and not the actual li

EDIT I am trying to understand why am I not getting the same result as when I simply console.log(Olist[i]). I have done this many times in the past, but I think there is something fundamental that I am missing here.

1
  • 1
    Try: console.log(`I was clicked ${Olist[i].innerHTML}`); Commented Dec 18, 2018 at 16:14

2 Answers 2

2

You're getting that value because the I was clicked ${Olist[i]} is calling .toString() on the HTMLLIElement instance. If you want to see the HTML for the element, try calling I was clicked ${Olist[i].outerHTML}.

const Olist = document.querySelectorAll('.drum li');


for (let i = 0; i < Olist.length; i++) {
  Olist[i].addEventListener('click', function(e) {
    console.log(`I was clicked ${Olist[i].outerHTML}`);
    console.log(`Olist[i].toString() => ${Olist[i].toString()}`);
  })
}
<ul class="drum">
  <li>A</li>
  <li>S</li>
  <li>D</li>
</ul>

Sign up to request clarification or add additional context in comments.

3 Comments

can you elaborate a little more on the .toString() part. I mean I am definitely not clear how this is happening, I feel like there is more to this? Any recommended reading maybe? Thanks much for your help!
@BradShaw When you concatenate an object, in this case HTMLLIElement, to a string, the object's .toString() method is called. All prototypes in JavaScript derive from the base Object prototype. The Object prototype defines a toString() method that your child prototypes can override. The HTMLLIElement prototype does not appear to override this. Please see developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… for more information.
@BradShaw Here's a fiddle for clarification, and some parallels to your question: jsfiddle.net/gyavskdo/3
0

Here's a simple solution.

// Convert a HTMLCollection to an array, then apply the following code for each item
// within the array.
Array.prototype.slice.call(document.querySelectorAll('.drum li')).map(li => li.onclick = () => {
  const string = li.outerHTML;
  console.log(string + ' Was clicked');
});
<ul class="drum">
 <li>A</li>
 <li>S</li>
 <li>D</li>
</ul>

Comments

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.