Reputation: 3601
I'm attempting to add an element by using:
let el = `<div></div>`;
document.body.appendChild(el);
I noticed that el
is shown as a 'string' in console.log. Should I be adding the element via createElement
instead?
code:
let topPos = (Math.random() * 100) + '%'
let leftPos = (Math.random() * 100) + '%'
let bubbleMd = `
<div class="bubble bubble-md"></div>
`;
let layer = document.getElementsByClassName('layer3')
layer.appendChild(bubbleMd).setAttribute(
'style',`top: ${topPos}; left: ${leftPos};`
);
Upvotes: 0
Views: 90
Reputation: 1
a) yes, you need to use createElement because appendChild expects a HTMLElement not a string, b) layer is a nodelist, so has no appendChild method
So:
let topPos = (Math.random() * 100) + '%'
let leftPos = (Math.random() * 100) + '%'
let bubbleMd = createElemnt('div');
bubbleMd.classList.add('bubble', 'bubble-md');
bubbleMd.style=`top: ${topPos}; left: ${leftPos};`;
let layer = document.getElementsByClassName('layer3')[0]; // note the [0]
layer.appendChild(bubbleMd);
Upvotes: 1