Search code examples
javascriptreplaceaddeventlisteneronchange

How to replace content with change addEventListener instead of adding


Hi I have some code where i'm inserting a span on a page each time a change is made to a dropdown item. What i want to achieve is the content inside the span to be changed/replaced each time a change in the dropdown is made. But what I'm currently getting is a new span being created each time instead. An example of how my code looks is below, any help on this would be appreciated.

doSomething.addEventListener('change', function() {
    document.querySelector('.className').insertAdjacentHTML("afterend", "<span>" + somethingDynamic + "</span>");
});


Solution

  • I needed the span content to be inserted into a certain place on the page so I created a new Div to be inserted onto the page where i needed it and then to replace the content inside it using innerHTML as suggested to get what I needed.

    doSomething.addEventListener('change', function() {
        document.querySelector('.className').insertAdjacentHTML("afterend", "<div class='new'></div>");
      document.querySelector('.new').innerHTML =  "<span>"+ dynamicContent + "</span>";
    });