skip to Main Content

I have the following html:

<div id="d1"></div>This is a text that <div id="d2"></div>needs to be manipulated

and two phrases from the text that indicates a start and end position, say in this example:

start = "a text"
end = "needs"

How can I use javascript to add a span element with a start tag just before the start phrase, and an end tag just after the end phrase, like this?

 <div id="d1">/div>This is <span id="phrase_1">a text that <div id="d2"></div>needs</span> to be manipulated

3

Answers


  1. use this

    const start = "a text"
    const end = "needs"
    
    
    const html = container.innerHTML
    
    const indexStart = html.indexOf(start)
    const indexEnd = html.lastIndexOf(end)
    
    const newHTML =
      html.slice(0, indexStart)
    + `<span>${html.slice(indexStart, indexEnd + end.length)}</span>`
    + html.slice(indexEnd + end.length)
    
    console.log(container.innerHTML = newHTML)
    span { color: red }
    <div id="container">
      <div id="d1"></div>This is a text that <div id="d2"></div>needs to be manipulated
    </div>
    Login or Signup to reply.
  2. It would be interesting to know in what kind of parent element your initial html is included in. Because, if you can target that element.

    if you can get the parent element, then you could do:

    parent.innerHTML.replace('a text', '<span>a text').replace('needs',  'needs</span>')
    
    Login or Signup to reply.
  3. Clean the tags first, you have extra /div> just after the <div id="d1"> tag.

    Its simple, just use String.prototype.replaceAll() function as mentioned in here.

    var previousText = document.getElementById('d1').innerHTML;
    var startTag = 'a text';
    var endTag = 'needs';
    var changedText = previousText.replaceAll(startTag, '<span>'+startTag).replaceAll(endTag, endTag + '</span>');
    console.log(changedText)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search