Dynamically create image for <li>

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • scarfpogi
    New Member
    • Oct 2014
    • 1

    Dynamically create image for <li>

    I want to create image on list <li> during runtime.

    Please help.

    Here is my code:
    Code:
    function myFunction() { 
    var ul = document.getElementById("list");
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(<img src=picture.jpg)); // I want the image to go here. any suggestion?
    ul.appendChild(li);
    Last edited by Frinavale; Oct 30 '14, 07:28 PM. Reason: Added the question posted in the title of the thread to the body of the thread so that the code post has context and also added code tags and corrected grammar.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    erm, you are aware that document.create TextNode() creates a literal text no matter what you put in (hence the name!) ?

    the solution: create an image element (just like you did with the <li> element)

    Comment

    • jmrker
      New Member
      • Dec 2012
      • 17

      #3
      One possible, of many available, solution...

      Code:
      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8" />
      <title> HTML5 page </title>
      </head>
      <body>
      <ul id="list"></ul>
      
      <script type="text/javascript">
      function myFunction(imageName,imageText) { 
        var ul = document.getElementById("list");
        var li = document.createElement("li");
        var img = document.createElement('img');
        img.setAttribute("src", imageName);
        img.setAttribute("width", "150");
        img.setAttribute("width", "125");
        img.setAttribute("alt", imageText);
      
        li.appendChild(img); // I want the image to go here. any suggestion?
        ul.appendChild(li);
      }
      window.onload = function() {
        myFunction("http://www.nova.edu/hpd/otm/pics/4fun/11.jpg","Exhausted");
        myFunction("http://www.nova.edu/hpd/otm/pics/4fun/21.jpg","Angry");
        myFunction("http://www.nova.edu/hpd/otm/pics/4fun/31.jpg","Embarrassed");
      }
      </script>
      
      </body>
      </html>

      Comment

      Working...