问题
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