My current project involves creating an embedded widget. Users will be required to insert an anchor
tag and JavaScript code on their page, which then dynamically renders content similar to how embedded tweets work.
<a href="http://localhost:3000/user/13"
target="_blank"
class="my-widget"
data-widget-type="profile"
data-widget-identifier="id"
data-identifier-value="13"
>Sayantan Das</a>
</div>
<script src="//localhost/my-widget/js/widget.js" async ></script>
The idea is that the widget.js
script would locate all elements with the class my-widget
and replace them with an iframe
.
widgets.js
!function(global, document) {
global.MyWidgets = global.MyWidgets || {};
for(let widgets = document.getElementsByClassName('my-widget'), i = 0; i < widgets.length; i++) {
console.log(widgets)
let element = widgets[i];
let span = document.createElement('span');
span.innerHTML = "Changed from widget " + i;
element.parentNode.appendChild(span);
element.parentNode.removeChild(element);
}
}(window, document);
However, I am facing an issue where if I remove an element within the loop, the loop ends prematurely. For example, if there are two elements with the class my-widget
, after removing one element, the loop only runs once. How can I ensure that all elements are properly replaced?