0

I have to create a function that accepts two parameters a selector and a string which will put each individual word within the text content of the selected element inside a new 'span' element. Each new 'span' element must be given a unique ID, formed by combining the prefix and a sequential integer (e.g. par0, par1 etc.). Also the function needs to handle the nested child elements...

Any help of creating this will be highly appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Lolek
  • 41
  • 6
  • 5
    So what did you try? Split on word boundry/space and loop over the list and wrap in span with the id. – epascarello Nov 03 '17 at 14:39
  • https://stackoverflow.com/questions/24786071/wrap-each-word-in-an-html-element or https://stackoverflow.com/questions/8609170/how-to-wrap-each-word-of-an-element-in-a-span-tag or https://stackoverflow.com/questions/12105059/how-to-wrap-all-text-into-unique-span-tag or tons of other questions – epascarello Nov 03 '17 at 14:40
  • the output would be word1word2 etc – Lolek Nov 03 '17 at 14:41

2 Answers2

0

If you are using jQuery it is not to hard. Something like this should work:

var sentence = "this is a sentence";
var words = sentence.split(" ");

$.each(words, function(i, w){
    $("#elementToAppendTo").append($("<span>").text(w));
});

Split the sentence by " " (space). The split function returns an array.

Iterate over the words array and for every word, rap it in a span element and then append to a certain html element with the id "elementToAppendTo".

jdlChicory
  • 79
  • 2
  • 12
0

I think this is what you are after.

First you need to select the DOM elements with document.querySelectorAll then iterate over the elements with the string.replace method, this uses regex to capture any words and replace them with the template (this being a span wrapper).

function doThing(selector, str) {
  document
    .querySelectorAll(selector)
    .forEach((element) => {
      element.innerHTML = str.replace(/(\w+)/g, `<span>$1</span>`);
    });
}

doThing('.latin', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.');
span {
  background-color: yellowgreen;
}
<div class="latin"></div>
Ed Knowles
  • 1,925
  • 1
  • 16
  • 24
  • it's return only the first ID and delete the remain text... further information is no span elements in the HTML. – Lolek Nov 03 '17 at 15:14
  • @lolek please can you show your current workings to further understand you problem? – Ed Knowles Nov 03 '17 at 18:15