JSFiddle - React, Tailwind, and code Playground
HTML
<p class="sentence">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Similique aliquam totam odit excepturi reiciendis quam doloremque ab eius quos maxime est deleniti praesentium. Quia porro commodi blanditiis iure dicta voluptatibus.</p>
<p><strong>Selected words:</strong> <span id="selectedWords"></span></p>
<button>Show in alert</button>
CSS
.sentence span:hover,
.highlight {
background: red;
}
JavaScript
/**
* Sentence element
* @var {Object}
*/
var $sentence = $('.sentence');
/**
* Selected words output element
* @var {Object}
*/
var $selected = $('#selectedWords');
/**
* Wrap each word in a sentence in a span
* @param {String} sentence
* @return {String}
*/
function wrapSentence(sentence) {
// Get element contents and split by whitespace
var words = $sentence.text().split(/\s+/);
// Create an empty array for storing wrapped elements
var wrapped = [];
// Loop through each word and wrap
for (var i = 0; i < words.length; i++) {
wrapped.push('<span>' + words[i] + '</span>');
}
// Combine words into a string
return wrapped.join(' ');
}
/**
* Find all selected words in $sentence element
* @return {Array}
*/
function getSelected() {
// Create an empty array for storing selected words
var selected = [];
// Find all spans with the highlight class
$sentence.find('span.highlight').each(function() {
// Push span values to array
selected.push($(this).text());
});
// Return results
return selected;
}
/**
* Override original html with wrapped
*/
$sentence.html(wrapSentence());
/**
* Handle click event for each span in sentence
*/
$sentence.on('click', 'span', function() {
// Add/remove the highlight class
$(this).toggleClass('highlight');
// Update the selected output
$selected.text( getSelected().join( ', ' ) );
});
/**
* Alert the user with selected words
*/
$('button').on( 'click', function() {
alert( getSelected() );
} );