Jamie Hutber
Jamie Hutber

Reputation: 28074

Selecting element with JS by data attribute which contains quotes inside it

Create an element with a data attr

<div class="component" data-bind="component: { name: "recently-viewed"}">

Now I want to select it using JS:

document.querySelector('div[data-bind*="component: { name: \"recently-viewed\""]')

How can I get this to return the element? I am unable to edit the markup.

Upvotes: 0

Views: 59

Answers (2)

StudioTime
StudioTime

Reputation: 23979

Switch your quotes:

console.log(document.querySelector('div[data-bind*="component: { name: \'recently-viewed\'}"]'))
<div class="component" data-bind="component: { name: 'recently-viewed'}">

document.querySelector('div[data-bind*="component: { name: \'recently-viewed\'"]')

Fiddle here

Upvotes: 1

Jamie Hutber
Jamie Hutber

Reputation: 28074

Also you could use the other mini quotes

document.querySelector(`div[data-bind*='component: { name: "recently-viewed"']`)

Upvotes: 0

Related Questions