How to replace specific tags that contains selected labels

为君一笑 提交于 2020-01-06 07:22:32

问题


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 either of "apple" or "banana", but other spans with "orange" or "kiwi" I don't want to select?

From:

<span class=>
"kiwi"
</span>

<span class=>
"apple"
</span>

<span class=>
"orange"
</span>

<span class=>
"banana"
</span>

To:

<button>
"apple"
</button>

<button>
"banana"
</button>

Code:

function replaceElement (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) {
  replaceElement(document.querySelector('span'), 'button');
}

回答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.

function replaceElement (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');
  }
}
<span class=>
"kiwi"
</span>

<span class=>
"apple"
</span>

<span class=>
"orange"
</span>

<span class=>
"banana"
</span>


来源:https://stackoverflow.com/questions/53803268/how-to-replace-specific-tags-that-contains-selected-labels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!