4

I have a situation where I need to pass a string with an apostrophe in it to a javascript function. This function then takes the string and uses it to find the 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 escaping the apostrophe like showElement('what\'s') but that did not seem to work. Is this possible at all?

2
  • 3
    As a general rule, I would say stay away from using apostrophe's in your element IDs. Commented Feb 19, 2010 at 5:39
  • 1
    i believe using apostrophes for an element ID is invalid html Commented Feb 19, 2010 at 5:42

3 Answers 3

5

Have a look at JavaScript Escape Characters

Try using a backslash \

Something like

showElement('what\'s') 

function showElement(element_id){ 
     document.getElementById(element_id).style.display = "block"; 
} 
Sign up to request clarification or add additional context in comments.

Comments

2

You have entirely different problem here. id attribute can't have ' symbols inside and you won't be able to search for such an id with getElementById. Escaping works though, just not in this case.

Comments

1
showElement("what's")

Double quote around string with single quote inside.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.