user3591618
user3591618

Reputation: 1

Span in Loop Javascript

I have the code

function splitString(stringToSplit, separator) {

var str= "It’s that time of year when you clean out your closets, dust off shelves, and spruce up your floors. Once you’ve taken care of the dust and dirt, what about some digital cleaning? Going through all your files and computers may seem like a daunting task, but we found ways to make the process fairly painless."
var myArray = stringToSplit.split(" ")



for (var i=0; i < myArray.length; i++)
{

}
var yourSpan = document.createElement('span');
yourSpan.innerHTML = "";

var yourDiv = document.getElementById('divId');
yourDiv.appendChild(yourSpan);

yourSpan.onmouseover = function () {
    alert("On MouseOver");

}

and for html I have

<div id="transcriptText"> It’s that time of year when you clean out your
closets, dust off shelves, and spruce up your floors. Once you’ve taken
care of the dust and dirt, what about some digital cleaning? Going
through all your files and computers may seem like a daunting task, but
we found ways to make the process fairly painless.</div>
<br>
<div id="divideTranscript" class="button">&nbsp;Transform the
Transcript!&nbsp; </div>T

I need the span creation inside the loop, I need to create a span, add the class and id attribute (which is different for each word - it includes the index of the array (i)) to the span element, add the word inside the span, add mouseover/mouseout event listeners to the span, add the span to the original div. Can anybody help me its not much I just am not sure how I should go about making these final changes.

Upvotes: 0

Views: 1964

Answers (2)

GameSmashDash _
GameSmashDash _

Reputation: 1

for (let i = 0; i < raceTraits.ability.length;i++){
        document.getElementById("Race").innerHTML +=  "<span id =" + i + ">" + "</span>";
}

/*you could use the value in the for loop and plugin "i" to make this easier*/

Upvotes: 0

Barmar
Barmar

Reputation: 781096

var yourDiv = document.getElementById('divId');
for (var i = 0; i < myArray.length; i++) {
    var yourSpan = document.createElement('span');
    yourSpan.innerText = myArray[i];
    yourSpan.id = "yourspan_" + i;
    yourSpan.className = "yourclass";
    yourDiv.appendChild(yourSpan);
    yourSpan.onmouseover = function () {
        alert("On MouseOver");
    }
}

Upvotes: 1

Related Questions