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

153
Views
Highlight an individual character of text block containing links and heading on mouse hover

I am trying to achieve that when hovering over a character, the character should change color. It should work on individual characters, links, headings etc.

My following code gives me result that I want but it removes the links and headings.

$cont = $('.words');
parts = $.map($cont.text().split(''), function(v) {
  return $('<span />', {
    text: v
  });
});
$cont.empty().append(parts);
.words span:hover {
  color: #F00
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="words">
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
  <a href="#link">LINK</a>
  <h1>
    Heading
  </h1>
  Stet clita kasd gubergren, no sea takimata sanctus e Lorem ipsum dolor sit amet.
</div>

JS Fiddle: http://jsfiddle.net/bvpodc6z/1/

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

Had to make some slight changes to html, namely adding a p tag around text thats not in heading or link : http://jsfiddle.net/kfbaz3gw/

$('.words').children().each( (index, el) => {
    $(el).html(function (i, html) {
      var chars = $.trim(html).split("");
      return  chars.map(c=>'<span>'+c+'</span>').join('')
  });
 })
about 4 years ago · Santiago Gelvez Report

0

Just map the characters separately for each text node so that it doesn't erase your DOM structure.

$('.words, .words *').contents().each(function() {
    if (this.nodeType == 3)
      $(this).replaceWith(escapeHTML(this.nodeValue).split('').map(c => `<span>${c}</span>`).join(''));
});

function escapeHTML(s) {
  return s.replace(/&/g, "&amp;")
          .replace(/</g, "&lt;")
          .replace(/>/g, "&gt;")
          .replace(/"/g, "&quot;")
          .replace(/'/g, "&#039;");
}
about 4 years ago · Santiago Gelvez 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!