Skip to content Skip to sidebar Skip to footer

How To Replace Specific Tags That Contains Selected Labels

I wish to replace some specific spans with buttons, and the spans that I wish to replace has the same class names. How could I replace the spans (to buttons) if they contains eith

Solution 1:

You can't select an element based on the inner text. But what you can do is that you can filter the span element based on its inner text content.

functionreplaceElement (source, tagname) {
    var range = document.createRange();
    var element = document.createElement(tagname);
    range.selectNodeContents(source);
    element.appendChild(range.extractContents());
    source.parentNode.replaceChild(element, source);
  }

var spans = document.querySelectorAll('span'), i;
for (i = 0; i < spans.length; ++i) {
  if(spans[i].textContent.match('apple') ||spans[i].textContent.match('banana') ){
  replaceElement(spans[i], 'button');
  }
}
<spanclass=>
"kiwi"
</span><spanclass=>
"apple"
</span><spanclass=>
"orange"
</span><spanclass=>
"banana"
</span>

Post a Comment for "How To Replace Specific Tags That Contains Selected Labels"