Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
Highlight the whole sentence

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 class="sentence">(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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!