JSFiddle - React, Tailwind, and code Playground

by russduza

HTML

<h4>1) DOM Exercise: Split a block of text into individual SPANs or DIVs</h4>
    <p>The following exercise contains a block of text that represents the
        written transcript of a video. Often, a transcript is provided with a
        video so viewers can read along, or so the video can be captioned.&nbsp;
    </p>
    <p>In this exercise, we'll be doing the first step in building an
        interface that could appear alongside a video player on a Web
        page.&nbsp; The idea is that each word in the transcript will highlight
        as the matching portion of the video is playing.</p>
    <p>In order to do this, each word must be in its own HTML SPAN (or DIV).
        In a real video transcript application, each SPAN would have a time
        value in seconds associated with it, and as that moment of the video
        played, we'd change the background color of the SPAN matching that time
        period. </p>
    <p> In a real application, we would also have the word be clickable, upon
        which the video would seek to the appropriate moment and play from
        there.&nbsp; We will do this in Unit 4 if this course, but you don't
        have to make the words clickable in this assignment.&nbsp; Instead,
        you'll make the words highlight (with a yellow background perhaps, or
        some other notable change in style) when the mouse is over the word. </p>
    <p>So, if the input text is <strong>Breaking News. Spring is here to
        stay.</strong> the HTML output would be something like:</p>
    <code>&lt;span class="word" id="word0"&gt;Breaking &lt;/span&gt;<br>
        &lt;span class="word" id="word1"&gt;News. &lt;/span&gt;<br>
        &lt;span class="word" id="word2"&gt;Spring &lt;/span&gt;<br>
        &lt;span class="word" id="word3"&gt;is &lt;/span&gt;<br>
        &lt;span class="word" id="word4"&gt;here &lt;/span&gt;<br>
        &lt;span class="word" id="word5"&gt;to &lt;/span&gt;<br>
        &lt;span class="word" id="word6"&gt;stay....

JavaScript

document.addEventListener('DOMContentLoaded', function () {
    console.log('document ready');
    document.getElementById('divideTranscript').addEventListener('click', function () {
        var text = document.getElementById('transcriptText').innerHTML;
        //explode the string into an array
        var array = text.split(" ");
        console.log(array);
        var html = '';
        document.getElementById('transcriptText').innerHTML = '';
        array.forEach(function (index, value) {
            var span = document.createElement('span');
            span.textContent = index + " ";
            span.setAttribute('class', 'word');
            span.setAttribute('id', 'word' + value);
            document.getElementById('transcriptText').appendChild(span);
        });
    });
}, false);