By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,040 Members | 1,815 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,040 IT Pros & Developers. It's quick & easy.

Dynamically create image for <li>

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

Please help.

Here is my code:
Expand|Select|Wrap|Line Numbers
  1. function myFunction() { 
  2. var ul = document.getElementById("list");
  3. var li = document.createElement("li");
  4. li.appendChild(document.createTextNode(<img src=picture.jpg)); // I want the image to go here. any suggestion?
  5. ul.appendChild(li);
Oct 30 '14 #1
Share this Question
Share on Google+
2 Replies


Dormilich
Expert Mod 5K+
P: 8,639
erm, you are aware that document.createTextNode() 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)
Oct 30 '14 #2

P: 17
One possible, of many available, solution...

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title> HTML5 page </title>
  6. </head>
  7. <body>
  8. <ul id="list"></ul>
  9.  
  10. <script type="text/javascript">
  11. function myFunction(imageName,imageText) { 
  12.   var ul = document.getElementById("list");
  13.   var li = document.createElement("li");
  14.   var img = document.createElement('img');
  15.   img.setAttribute("src", imageName);
  16.   img.setAttribute("width", "150");
  17.   img.setAttribute("width", "125");
  18.   img.setAttribute("alt", imageText);
  19.  
  20.   li.appendChild(img); // I want the image to go here. any suggestion?
  21.   ul.appendChild(li);
  22. }
  23. window.onload = function() {
  24.   myFunction("http://www.nova.edu/hpd/otm/pics/4fun/11.jpg","Exhausted");
  25.   myFunction("http://www.nova.edu/hpd/otm/pics/4fun/21.jpg","Angry");
  26.   myFunction("http://www.nova.edu/hpd/otm/pics/4fun/31.jpg","Embarrassed");
  27. }
  28. </script>
  29.  
  30. </body>
  31. </html>
  32.  
Jan 1 '15 #3

Post your reply

Sign in to post your reply or Sign up for a free account.