Reputation: 1015
How to create element li img tag in ul tag using javascript ?
I want to create
<li id="123">
<img src="https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif"/>
</li>
inner
<ul id="placehere">
But not work, How can i do that ?
https://jsfiddle.net/btz69dyk/2/
<body>
<script type="text/javascript">
window.onload=function(){
var elem = document.createElement("li");
elem.setAttribute("id", "123");
var elem = document.createElement("img");
elem.setAttribute("src", "https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif");
elem.setAttribute("height", "");
elem.setAttribute("width", "");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(elem);
}
</script>
<ul id="placehere">
</ul>
</body>
Upvotes: 0
Views: 1739
Reputation: 36609
Append
image
element toli
element first and then appendli
element inul
element.
In your example, you are creating elements in same variable(elem
) hence second element will over-ride the earlier created element(variable will hold later element). Append image
element to li
element before updating it in DOM
, it will trouble DOM
structure only once..
Try this:
window.onload = function() {
var li_elem = document.createElement("li");
li_elem.setAttribute("id", "123");
var img_elem = document.createElement("img");
img_elem.setAttribute("src", "https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif");
img_elem.setAttribute("height", "");
img_elem.setAttribute("width", "");
img_elem.setAttribute("alt", "Flower");
li_elem.appendChild(img_elem);
document.getElementById("placehere").appendChild(li_elem);
}
<ul id="placehere">
</ul>
Upvotes: 2
Reputation: 1051
var listEle = document.createElement("li");
listEle.setAttribute("id", "123");
var elem = document.createElement("img");
elem.setAttribute("src", "https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif");
elem.setAttribute("height", "");
elem.setAttribute("width", "");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(listEle).appendChild(elem);
Upvotes: 1
Reputation: 68393
Problem is these 4 lines
var elem = document.createElement("li");
elem.setAttribute("id", "123");
var elem = document.createElement("img");
elem.setAttribute("src", "https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif");
here you are creating the same elem
element again with same variable name so li
is lost
change it to
var elem1 = document.createElement("li");
elem1.setAttribute("id", "123");
var elem = document.createElement("img");
elem.setAttribute("src", "https://upload.wikimedia.org/wikipedia/commons/5/53/Loading_bar.gif");
elem.setAttribute("height", "");
elem.setAttribute("width", "");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(elem1);
elem1.appendChild(elem);
Upvotes: 2