简体   繁体   中英

Append child <img> to <a> in JavaScript

Here is my code:

let a = document.createElement('a');
a.role = "menuitem";
a.tabindex = "-1";
a.href = "#";
a.onclick = function() {reloadPageWithChanges()};
a.innerHTML = stories["Chapter1"];
let img = document.createElement('img');
img.src = `pictures/cars/car1.png`;
img.style.marginRight = "3px";
img.style.marginLeft = "3px";
a.appendChild(img);
body.appendChild(a);

What this code does is that it creates a link that onclick reloads the page (with some small changes in the UI). This link contains the name ( stories["Chapter1"] ) and a picture next to it. However, this picture is always positioned on the right side from the text. I want it to be placed on the left side, so that all of these links (if there is more of them) have pictures left aligned. Is there any way to do that, using JavaScript's DOM?

You can use a.prepend(img); instead of a.appendChild(img);

 let a = document.createElement('a'); a.role = "menuitem"; a.tabindex = "-1"; a.href = "#"; a.onclick = function() { //reloadPageWithChanges() }; a.innerHTML = "myChapter"; //stories["Chapter1"]; let img = document.createElement('img'); img.src = `pictures/cars/car1.png`; img.style.marginRight = "3px"; img.style.marginLeft = "3px"; a.prepend(img); document.body.appendChild(a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM