Passing an apostrophe string to a javascript function

I have a situation where I need to pass a string with an apostrophe into it in a javascript function. Then this function takes a string and uses it to search for an element by id in the DOM. As an example, I need to call:

showElement('what's')

function showElement(element_id){
     document.getElementById(element_id).style.display = "block";
}

I tried to escape the apostrophe like showElement ("what"), but this does not seem to work. Is this even possible?

+3
source share
3 answers

Here you have a completely different problem. An attribute idcannot contain 'characters inside, and you cannot find such an identifier using getElementById. However, the escape works, just not in this case.

+2
source

JavaScript Escape Characters

\

-

showElement('what\'s') 

function showElement(element_id){ 
     document.getElementById(element_id).style.display = "block"; 
} 
+5
showElement("what's")

Double quote around the line with one quote inside.

+1
source

Source: https://habr.com/ru/post/1733480/


All Articles