Let’s say I have something like:
<div id="foo">
Lorem ipsum dolor sit amet, consectetur adipiscing elit <span id="some-span"></span>
</div>
How could I add a span to a specific position of the text above? I don’t want the span with the id some-span to lose its event listeners.
2
Answers
You can add a new span element to a specific position of the text content within the div element with the id of "foo" without losing the span element with the id of
some-span
and its event listeners, you can use theinsertAdjacentHTML
method in JavaScript.Demo:
In the avobe code, first get references to the div element with the id of
foo
and the span element with the id ofsome-span
. Then get the text content of the div element, find the index of the textconsectetur
within the text content, and split the text content into two parts, one before the textconsectetur
and one after.Next, a new span element with the desired content is created and assign it to the
newSpan
variable. UseinsertAdjacentHTML
method twice to insert the content of the after variable and thenewSpan
variable into the div element, which will effectively add the new span element to the desired position.Finally, get a reference to the new span element with the id of
new-span
and use theinsertBefore
method to insert it before thesomeSpan
element, ensuring that the existing span element and its event listeners are not affected.