-3

I am trying to have it so when I click on a word, it'll be marked out with a black background. Right now, I am wrapping each word in a sentence in its own span, but I would like to create a span for each word in a block of text. Any ideas on how to go about doing that?

Here is my code right now

document.querySelectorAll('span').forEach(span=> 
    span.onclick = () => {
    span.style.background = '#000';
})

HTML

<span>these </span>
<span>are </span>
<span>some </span>
<span>words </span>
<span>for </span>
<span>a </span>
<span>test </span>
Ivy Chen
  • 35
  • 4
  • 2
    Did you try and use your favorite search engine and search "wrap each word in span JavaScript"? – epascarello Jun 28 '21 at 15:05
  • Yeah I did, they were mostly jquery answers. – Ivy Chen Jun 28 '21 at 15:08
  • 1
    https://stackoverflow.com/a/15602535 https://stackoverflow.com/a/50135988 https://stackoverflow.com/a/66380709 https://stackoverflow.com/a/24487987 https://stackoverflow.com/a/55557908 – VLAZ Jun 28 '21 at 15:12

1 Answers1

2

Something like this?

const text = "These are some words for a test";
 
text.split(' ').forEach(word => {                  // loop over every word
  const element = document.createElement("span");  // create element "span"
  element.innerText = word;                        // set its content to word
  element.onclick = () =>                          // onclick handler
    element.style.background = '#000';             // action
  document.body.appendChild(element);              // add element to dom
});
span {
  color: orange;
  margin-left: 3px;
}
stacj
  • 1,103
  • 1
  • 7
  • 20