1

I was looking through Stack Overflow and came across this link (How to get a word under cursor using JavaScript?)

They have the code:

<p>Each word will be wrapped in a span.</p>
<p>A second paragraph here.</p>
Word: <span id="word"></span>

<script type="text/javascript">
    $(function() {
        // wrap words in spans
        $('p').each(function() {
            var $this = $(this);
            $this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
        });

        // bind to each span
        $('p span').hover(
            function() { $('#word').text($(this).css('background-color','#ffff66').text()); },
            function() { $('#word').text(''); $(this).css('background-color',''); }
        );
    });
</script>

When I tried this out, I realized this code will only work with paragraph tags. How should I edit the Javascript/Regex of this code to make it work will all tags(h1,h2,h3)?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
idude
  • 4,654
  • 8
  • 35
  • 49

1 Answers1

1

jsFiddle Demo

Make a few adjustments. Change the selector to include h1,h2,h3

$('p,h1,h2,h3').each(function() {

And then also do this lower for the hover. You will need to use find on the set for the nested spans.

$('p,h1,h2,h3').find("span").hover(
Travis J
  • 81,153
  • 41
  • 202
  • 273