0

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\\')\']')
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
  • 2
    *"I cannot use double quotes, due to the effect that the querySelector is covered with double quotes "."* I have no clue why that means you can not use them.... – epascarello Sep 28 '20 at 02:32

2 Answers2

4

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

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>
symlink
  • 11,984
  • 7
  • 29
  • 50