skip to Main Content

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


  1. 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 the insertAdjacentHTML method in JavaScript.

    Demo:

    let foo = document.getElementById('foo');
    let someSpan = document.getElementById('some-span');
    
    let textContent = foo.textContent;
    let index = textContent.indexOf('consectetur');
    let before = textContent.slice(0, index);
    let after = textContent.slice(index);
    
    let newSpan = '<span id="new-span">New Span</span>';
    
    foo.insertAdjacentHTML('beforeend', after);
    foo.insertAdjacentHTML('beforeend', newSpan);
    
    const newSpanElement = document.getElementById('new-span');
    foo.insertBefore(newSpanElement, someSpan.nextSibling);
    #new-span{
     color:red;
    }
    <div id="foo">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit <span id="some-span"></span> 
    </div>

    In the avobe code, first get references to the div element with the id of foo and the span element with the id of some-span. Then get the text content of the div element, find the index of the text consectetur within the text content, and split the text content into two parts, one before the text consectetur and one after.

    Next, a new span element with the desired content is created and assign it to the newSpan variable. Use insertAdjacentHTML method twice to insert the content of the after variable and the newSpan 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 the insertBefore method to insert it before the someSpan element, ensuring that the existing span element and its event listeners are not affected.

    Login or Signup to reply.
  2. const foo = document.querySelector('#foo')
    const span = document.querySelector('#some-span')
    
    span.addEventListener('click', () => console.log('working'))
    
    const text = foo.childNodes[0]
    foo.removeChild(text)
    foo.insertAdjacentHTML('beforebegin', text.wholeText.replace(/dolor/, '<span class="green">dolor</span>'))
    #some-span {
      background: red;
      width: 100px;
      height: 100px;
      display: block;
    }
    
    .green {
      color: green;
    }
    <div id="foo">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit <span id="some-span"></span>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search