Reputation: 17
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
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
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