skip to Main Content

I cannot figure out how to console log the innerText inside of the li and not the p that is nested inside of the li.

HTML

<ul id="list">
    
      <li>Tank
        <p>this is tank</p>
      </li>
    
    
      <li>Warrior
        <p>this is warrior</p>
      </li>
    
    
      <li>Ninja
        <p>this is ninja</p>
      </li>
    
  </ul>

JavaScript

const listChoice = document.querySelectorAll('li')

listChoice.forEach(cls => {
  cls.addEventListener('click', (e) => {
    const choice = e.target.innerText

    console.log(choice)

    if (choice === 'Tank') {
      console.log('You chose tank')
    }
  })
})

I can’t get my choice variable to equal the target innerText so that the console.log(‘you chose tank’) shows in the console.

I’ve tried using firstChild and it logs "Tank "

2

Answers


  1. Chosen as BEST ANSWER

    I found a way to get it to work by checking the typeof choice then using the .includes method to see if 'Tank' is included in the string.

     if (choice.includes('Tank')) {
      console.log('You chose tank')
    }
    

  2. You’re trying to log the innerText of the li elements when they are clicked. However, since the li elements also contain p elements, you need to ensure that you’re getting the correct text. To do this, use the textContent property of the li element, which retrieves the text content within the li element, and then use trim() to remove any leading or trailing white spaces.

    With this modification, you should be able to capture the text within the li elements and make your conditional statement work as expected. In this code, when you click on an li element, it logs the text content of that li element and checks if it equals "Tank" to log a corresponding message.

    Here’s what you should edit:
    const choice = cls.textContent.trim();

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search