Amine Debaya
Amine Debaya

Reputation: 13

JavaScript querySelector error: 'Document': '[rowIndex=0]' is not a valid selector

I'm making a public library project where you can add books and remove them from a table. I'm having trouble removing the table rows however. To add the elements I have set it so that the remove button and the row have the same attribute number (btnIndex == rowIndex) and as you can see from below I'm trying to set it up so that the row is removed when the button is clicked.

function removeElement () {
        let buttonAtt = this.getAttribute("btnIndex");
        const deletedRow = document.querySelector(`[rowIndex=${buttonAtt}]`);
        console.log(deletedRow);
        table.removeChild(deletedRow);
}

However, when I add an element to the table and then I click the Remove button, I get this error.

Error:

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '[rowIndex=0]' is not a valid selector.

I'm not sure what the problem exactly is. I would really appreciate your help. Thank you.

Upvotes: 0

Views: 204

Answers (1)

esqew
esqew

Reputation: 44710

Wrap the attribute value you're targeting in quotes:

function targetRowIndex(index) {
  document.querySelector(`[rowIndex="${index}"]`).style.background = "red";
}

document.querySelector('button').addEventListener('click', function() {
  targetRowIndex(0);
});
<div rowIndex=0>Content here</div>
<button>Run function &rarr;</button>

Upvotes: 4

Related Questions