Reputation: 49
I have the following innerHTML in element id "word":
<span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span
I would like to create a function (wordReverter) that removes all of the tags, leaving in the above example, only the word "hello". Any help would be greatly appreciated, thank you!
function wordReverter() {
var word = document.getElementById("word").innerHTML;
//var rejoinedWord = rejoined word with <span> tags removed
document.getElementById("word").innerHTML = rejoinedWord;
}
Upvotes: 1
Views: 65
Reputation: 1327
If you have the containing element, you can target it and retrieve it's textContent
, otherwise, you can select all the elements of interest and retrieve their content as below:
function wordReverter() {
let letters = document.querySelectorAll('.white,.green')
return Array.from(letters).map(l=>l.textContent).join('')
}
console.log(wordReverter())
<span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span>
Upvotes: 0
Reputation: 4539
Get the innerText and use it as a new innerHtml like below
(function wordReverter() {
var word = document.getElementById("word").innerText;
document.getElementById("word").innerHTML = word;
})()
<div id="word">
<span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span>
</div>
Upvotes: 2