Get HTML div element by its attribute and value using query selector API

I have below div in my HTML.

<div row-index="0" /div>
<div row-index="1" /div>

I have to select specific div from above using its attribute. I am trying to do below in my typescript code. I get this index 0, 1 from another object.

const value = event.rowIndex;  -->line 1
const elem = document.querySelector('[row-index= value]'); -->line 2

The ‘value’ in line 2 upon hovering in my webstorm IDE says cannot find declaration to go to. I want it to use value from line1. Do I have to escape it using some backslash or quotations or something?

>Solution :

You can’t just drop a variable into a selector like that. You’ll need to use concatenation or a template literal.

querySelector('[row-index="' + value + '"]')

Leave a Reply