Backslash escapee 140211

Hello expert,

Working on using innHTML to change add some text to a page.

Ran onto the code copied below.  In the code
alert("The content of the first DIV element is " + "\"" + oVDiv.innerHTML + "\".");
it is understood that the backslash cancels out the next character.
So instead of  "\"" what is passed to the browser is "". But why use the backslash?
What would be wrong with just using ""?


Allen in Dallas

<!DOCTYPE html>

  <title>Show First DIV Content</title>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
  <meta http-equiv="X-UA-Compatible" content="IE=8">

  <div id="oDiv1">Div #1</div>
  <div id="oDiv2">Div #2</div>
  <div id="oDiv3">Div #3</div>
  <input type="button" value="Show First DIV Content" onclick="fnGetId()"> 
  <script type="text/javascript">
    function fnGetId() {
      // Display the content of the first DIV element in the collection.
      var oVDiv=document.getElementById("oDiv1");
      alert("The content of the first DIV element is " + "\"" + oVDiv.innerHTML + "\".");


Open in new window

Allen PittsBusiness analystAsked:
Who is Participating?
DualCoolConnect With a Mentor Commented:
** the short answer is your code will fail if you just use "" and when you click your button nothing will happen

you must have the proper syntax to achieve the desired result.

the backslashes are used to "escape" the quote characters inside of the string and to show where the first and last part of the string ends and the dynamic text starts/ends. the plus signs allow the dynamic text inside of the div to be used in the alerted string. this is called string concatenation.

Experiment with the different ways and alert the result to see the differences

hope this helps
it don't cancel it, it allow you to use it

you can't have : """
because " start AND end a string

So if you want to use " inside a string set with double quotes you need to escape the char "

OR use simple quote around: 'my string'
alert('The content of the first DIV element is "' + oVDiv.innerHTML + '".');

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.