javascriptjqueryhtmljquery-append

Why I can't correctly append a tag having the id specified? Is it a character escaping problems?


I am pretty new in JavaScript and Jquery and I have the following problem that I think could be related to some character escaping.

So I have this simple JQuery script:

<script>
    $( document ).ready(function() {
      //alert(exludeUserAgent());
      if(exludeUserAgent()) {
          //$( "#sezioneBenvenuto" ).remove();
          //$( "#sezioneLogo" ).remove();
          $( "#sezioneLogin" ).remove();

          $( ".container" ).append( "<section id="sezioneErrore"><p>TEST</p></section>" );
      }
    });
</script>

The problem is that when the append statment is performed it give me the following error:

**SCRIPT1006: Previsto ')'**

on this line:

$( ".container" ).append( "<section id="sezioneErrore"><p>TEST</p>

If I remove the id="sezioneErrore" and I append a section tag without the id definition I have no problem.

Why? What am I missing? The problem could be the " character of the id="sezioneErrore" ? If yes how can I try to escape it?


Solution

  • The string is breaking as you've used double quote that is causing the syntax error.

    To solve this error, you can either

    1. Use double quote inside single quote(and vice versa)
    2. Escape the quotes inside the string

    Examples:

    Use single quotes outside

    $(".container").append('<section id="sezioneErrore"><p>TEST</p></section>');
    

    Or single quotes inside double quotes

    $(".container").append("<section id='sezioneErrore'><p>TEST</p></section>");
    

    If you want to use double quotes inside double quote, escape it

    $(".container").append("<section id=\"sezioneErrore\"><p>TEST</p></section>");
    

    Same for single quotes

    $(".container").append('<section id=\'sezioneErrore\'><p>TEST</p></section>');