简体   繁体   中英

How do you add an element next to another using JavaScript

I have the code to append an element to another via classname. It works however it no use as I'm not able to distinguish this appended element from it's parent. It's all under the parents <a href tag.

Is it possible to add an element next to another element so it's within it's own tag hence I can identify it separately?

I'm getting all the parents elements via classname.

const emailElements = document.getElementsByClassName('email');
[...emailElements].map(el => {
const image = 
document.createElement('img');
image.setAttribute('src', 'https://i.ibb.co/QbPNFwB/t.jpg');   
el.append(image);
});

the best way to distingush elements is by 'id'... as such - the answer is just to put an id tag on each img element so you have 100% control over each image.

const emailElements = Array.from(document.getElementsByClassName('email'));
emailElements.map(el => {
const image = 
document.createElement('img');
image.setAttribute('src', 'https://i.ibb.co/QbPNFwB/t.jpg');   
image.setAttribute('id', `image${emailElements.indexOf(el)}`);   
el.append(image);
});

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