2 Replies Latest reply on Sep 21, 2016 2:44 AM by Heimdaal

    Creating HTML tags dynamically in JS for my panel (Syntax help)

    Heimdaal Level 1

      I'm tryinng to dynamically generate a UI for my panel. Creating the tags work just fine with the code below - the problem is the syntax for the background-image.


      // Construct HTML tags dynamically and append to content container
      for (var i = 0; i < myList.length; i++){
          var html = "";
          html += "<button class='lol'>";
          html += "<span class='lol2' style='background-image: url(" + myList[i].icon + ")'></span>"; // Syntax broken here
          html += "<p class='lol3'>" + myList[i].text + "</p>";
          html += "</button>";


      The tags are generated just fine - but I do not get the background-image property for them - most likely because the syntax for the attribute url() is broken. Also worth mentioning is that myList[i].icon contains a string - so this is not a data problem.

        • 1. Re: Creating HTML tags dynamically in JS for my panel (Syntax help)
          DBarranca Level 4

          Isn't the background image url a string itself? Try adding extra quotes in there:


          var html = "<span class='lol2' style='background-image: url(\"" + myList[i].icon + "\")'></span>"; 


          Had to escape them otherwise is a mess.

          Hope this helps,


          Davide Barranca

          1 person found this helpful
          • 2. Re: Creating HTML tags dynamically in JS for my panel (Syntax help)
            Heimdaal Level 1

            That helped - the script no longer runs due to a syntax error.
            However the image is still not loaded. I printed that part of the HTML and the syntax looks fine to me:

            <span class='topcoat-icon--large' style='background-image: url("../img/myImage.png")'></span>


            I also tried another case and edited my main.js with this syntax instead

            html += "<span class='lol2' style=\"background-image: url('.." + myList[i].icon + "')\"></span>";


            Printing the html var I then get:

            <span class='topcoat-icon--large' style="background-image: url('../img/myImage.png')"></span>

            Which also looks fine


            I've also tried this syntax on a button, with the onclick-property pointing to a simple function in main.js that only has an alert() - still not working



            NVM - The problem now at the end was due to the paths in the url-attribute being wrong. I created these tags manually in my index.html and then previewed it in a browser. That way I was able to pinpoint the problem much easier.