Home > Mobile >  Issue with alignment when programmatically creating elements
Issue with alignment when programmatically creating elements

Time:01-14

I'm trying to create the below programmatically. This part is easy and done.

   <a href="#"  style="border-radius: 0;">
        <img src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/240/apple/325/disguised-face_1f978.png" style="height: 30px; width: 30px;">
        &nbsp;
        The current link item
    </a>

The issue is that when I do it, it ends up like this:

<a href="#"  style="border-radius: 0;">
    The current link item
    <img src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/240/apple/325/disguised-face_1f978.png" style="height: 30px; width: 30px;">
</a>

The text "The current link item" is above the image instead of below it. How would I change it to make the text below the img tag so that it appears like this:

[img] text

instead of like this:

text [img]

also looking to add the &nbsp; to make a space between the image and text

function setAttributes(el, attrs) {
    for(var key in attrs) {
        el.setAttribute(key, attrs[key]);
    }
}
          
test = document.getElementById('test');


let a = document.createElement('a');
let img = document.createElement('img');

if (element['icon_url'] === null) {
    img.src = 'https://cdn.pixabay.com/photo/2020/02/10/11/12/smiley-4836191_1280.png';
} else {
    img.src = element['icon_url'];
}

let classesToAdd = [
    'list-group-item', 
    'list-group-item-action',
    'd-flex',
    'justify-content-start',
    'align-items-center'
];

a.classList.add(...classesToAdd);

setAttributes(a, {
    'href': '#',
    'id': element['id']
});

a.textContent = element['name'];

a.appendChild(img);
test.appendChild(a);
<div id="test"></div

CodePudding user response:

You can use the document.createTextNode(data) function with document.appendChild(aChild).

Read more about MDN | Document.createTextNode().

This is what this could look like:

let test = document.getElementById("test");

let a = document.createElement("a");
let img = document.createText("img");
img.src = "https://MY_IMAGE";

a.appendChild(img); // append img element first
a.appendChild(document.createTextNode("<-- Text Aside Img")); // append text node AFTER img element
test.appendChild(a);

CodePudding user response:

to add elements before the existing children you can use

a.prepend(img);

instead of

a.appendChild(img);

read more about prepend

  • Related