Home > Back-end >  Highlight the whole sentence
Highlight the whole sentence

Time:07-12

How Can I highlight the whole sentence just by click at only one word withen that sentence.

sentence = [];
var sentence = $('.sentence').html().split(/\s /),

result = [];
 for (var i = 0; i < sentence.length; i  )

 result[i] = '<span>'   sentence[i]   '</span>';
var a = sentence[i];

}

$('.sentence').html(result.join(' '));

if (a.indexOf(" ")   1) 
alert('fail: '   a);

} else {

  sentence.push(a);
}

$('.sentence').on('click', 'span', function() {
  $(this).addClass('highlight');
});

$('button').click(function() {
  alert(sentence);
});

$('$selectedsentence').innerHTML = sentence;
.sentence span:hover,
.highlight {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p >(1)Lorem ipsum dolor sit amet. (2) consectetur adipisicing elit. (3)Similique aliquam totam odit excepturi. (4) reiciendis quam doloremque ab eius quos.</p>



Selected sentence:
<p id="selectedsentence"></p>

<button>Show in alert</button>

CodePudding user response:

If you split the sentences into <span> elements you can add a click handler and control the styles of each individually.

let paragraph = document.getElementById('test');
paragraph.innerHTML = '<span>'   paragraph.textContent.trim().replaceAll(/\.\s/g,'. </span><span>')   '</span>';

let sentences = paragraph.querySelectorAll('span');
sentences.forEach(s => s.addEventListener('click', highlight));

function highlight(event) {
  sentences.forEach(s => s.classList.remove('selected'));
  event.target.classList.add('selected');
}
span.selected {
  background: yellow;
}
<p id="test">
  (1) Lorem ipsum dolor sit amet. (2) consectetur adipisicing elit. (3) Similique aliquam totam odit excepturi. (4) reiciendis quam doloremque ab eius quos.
</p>

CodePudding user response:

Here is a worked example:

let sentence = $('.sentence').text();

sentences = sentence.split('.')
$('.sentence').html('');

for (let s of sentences) {
  $('.sentence').append('<span>'   s   '.</span>')
}

$('.sentence span').on('click', function() {
  $(this).addClass('highlight').siblings().removeClass('highlight');
});
.sentence span:hover,
.highlight {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p >
  (1)Lorem ipsum dolor sit amet. (2) consectetur adipisicing elit. (3)Similique aliquam totam odit excepturi. (4) reiciendis quam doloremque ab eius quos.
</p>

  • Related