Getting the highlighted text inside selected element only.

Posted by ashays on Stack Overflow See other posts from Stack Overflow or by ashays
Published on 2010-04-12T22:19:10Z Indexed on 2010/04/12 22:23 UTC
Read the original article Hit count: 339

My goal is to be able to get the highlighted text within a document, but only if that text is within a given section, and then apply a certain style to that selected text after clicking a div tag. I'll explain what I mean:

So, having looked at window.getSelection() and document.selection.createRange().text, I attempted to use elmnt.getSelection() or elmnt.selection.createRange().text for some HTML element, elmnt. However, it doesn't seem to work, so that idea seems pretty null. This means I can't use this idea to determine the text that is highlighted within a given location. In case this doesn't make sense, essentially, I want html code that looks like this:

<body>
  <div id="content">Stuff here will not be effected</div>
  <div id="highlightable">Stuff here can be effected when highlighted</div>
  <div id="morecontent">Stuff here will also not be effected</div>
</body>

So that whenever I've highlighted text, clicking on a specified div will apply the proper CSS.

Now, on to the div tags. Basically, here's what I've got on that:

$('.colorpicker').click( function(e)
{
  console.log(getSelectedText());
}

Eventually, all I want this to highlight the selected text and have the div tag change the color of the selected text to that of the respective div tag that I've selected. Neither of these seems to be working right now, and my only guess for the reason of the div tag is that it unhighlights whatever I've got selected whenever I click on the div tag.

Fallbacks:

  • If there is more than one time that 'abc' is found on the page and I highlight to color 'abc', I would like that only that copy of 'abc' be highlighted.

I know this is a lot in one question, but even if I could get a little head start on this idea, my next personal project would be going a lot more smoothly. Thanks. :)

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about html