0

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);
});
Andy S
  • 1
  • 2
  • what do you mean with "next" is it an element after **another** one ? – Abdessamad Jadid Aug 26 '20 at 15:45
  • Does this answer your question? [How to insert an element after another element in JavaScript without using a library?](https://stackoverflow.com/questions/4793604/how-to-insert-an-element-after-another-element-in-javascript-without-using-a-lib) – FluffyKitten Aug 26 '20 at 15:47
  • Yes one after another or next too, similar to append but not within the parent elements tag as then you can't distinguish this new element from the parent. – Andy S Aug 26 '20 at 15:50
  • @AndyS it sounds like you want to insert it after another element - that already has a good answer here on StackOverflow, see the link I gave you! – FluffyKitten Aug 26 '20 at 15:51
  • the answer of your queston is here [(https://stackoverflow.com/questions/4793604/how-to-insert-an-element-after-another-element-in-javascript-without-using-a-lib)] – Abdessamad Jadid Aug 26 '20 at 16:36

1 Answers1

1

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);
});
altruios
  • 986
  • 1
  • 10
  • 29