1

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;
}
1

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Yes to .innerText. No to that ridiculous (and named?) self-executing function. Actually, I even found some Browsers failing unless the self-executor is like (function(){ }()); or (()=>{ }());.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.