user3580096
user3580096

Reputation: 17

Cannot escape quotes within a function

How can I escape these quotes?

I tried it like this. However, I cannot use double quotes, due to the effect that the querySelector is covered with double quotes ".

document.querySelector('[onclick=\'tabbed(\\'tabsrc-cnt2\\')\']')

Upvotes: 0

Views: 76

Answers (2)

symlink
symlink

Reputation: 12208

You can put the param in a data attribute and search for it that way.

document.querySelector('[data-param="tabsrc-cnt2"]')

function tabbed(val){
  console.log(val)
}
<div onclick='tabbed("tabsrc-cnt2")' data-param='tabsrc-cnt2'>Click Me</div>

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 371168

You can pass a template literal into querySelector instead. As the template literal quote is `, both " and ' can be used without needing to be escaped.

console.log(
  document.querySelector(`[onclick="tabbed('tabsrc-cnt2')"]`)
);
<button onclick="tabbed('tabsrc-cnt2')">button</button>

An easier to read option would be to select an element whose attribute contains tabsrc-cnt2:

console.log(
  document.querySelector(`[onclick*="tabsrc-cnt2"]`)
);
<button onclick="tabbed('tabsrc-cnt2')">button</button>

That said, if this is your own site, it would be better to avoid inline handlers entirely, they have too many problems (including ugly escaping issues like this one) to be worth using nowadays.

Upvotes: 4

Related Questions