Search code examples
javascriptinnerhtmlqueryselector

Setting data by using innerHTML can't bring data with querySelector


const li = document.createElement('li');
li.innerHTML = `
  <i class="fa fa-square-o item btn emptyButton" aria-hidden="true"></i>
  <i class="fa fa-check-square-o item btn checkedButton dis-non" aria-hidden="true"></i>
  <span class='item' id = '${anArray.length + 1}'>${INPUTVALUE}</span>
  <i class="fa fa-trash-o btn removeButton item" aria-hidden="true"></i>
`;

I was setting HTML data like above, then I was having trouble with getting data. I wanted to use querySelector like following with span and its id:

document.querySelector('span#2')

But I could not get anything so I had to do crazy work like:

ET.arentElement.arentElement.parentElement.previousElementSibling.firstElementChild.innerText;

This is not from the example code, but because this is the worst so I wanted to use this as an example.


Solution

  • Your ID cannot start with a number.

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

    Use something like:

    document.querySelector('#my-data-2')
    

    and your span:

    <span class='item' id ='my-data-${anArray.length + 1}'>
    

    (all inside the back tick, as in your code).