tags:

views:

478

answers:

4

using Javascript, it is easy to programatically select the text inside a textarea or input text element. How about for

<span>The quick brown fox jumps over the lazy dog</span>

is it possible to use JavaScript to select the words "quick brown fox"? Or select the whole sentence?

A: 

in css you could create a .highlight class

.highlight{
  background-color:yellow;
}

in javascript you could add the .highlight class to the elements you wish to highlight

<getSpanElement>.className='highlight';

this text is then highlighted, though it is not selected.

Matthew Vines
A: 

Highlight or select? I think you actually want to select not to highlight.

Highlight... yes! Set the proper CSS properties of the span element, for instance foreground and background color.

Edit: That is called selecting. Sorry, I don't know of any way to do it.

Marius Burz
coz when i say "selecting", some users thought it meant "getting the value of".
動靜能量
+1  A: 

You will need some way to manipulate the span tag. Such as an id, but then in javascript I would edit some of the style properties. You could have a property for everything you want to highlight like what is shown below.

.HL {
    background: #ffff99; 
    color: #000000;
}

If you do that then you will need to get a reference to the specific tag.

DocumentgetElementsByTagName("title")

Otherwise Document.getElementByID("ID") is good for unique ids. Then using setAttribute(name, value) To change the class to the one given.

This is just a simple example but there are many ways to do this.

<span id="abc" class=""> Sample </span>
var temp = Document.getelementByID("abc");
temp.setAttribute('class', 'HL');
maleki
+4  A: 

Courtesy of http://www.sitepoint.com/forums/showthread.php?t=459934

<script type="text/javascript">
    function fnSelect(objId) {
     fnDeSelect();
     if (document.selection) {
     var range = document.body.createTextRange();
            range.moveToElementText(document.getElementById(objId));
     range.select();
     }
     else if (window.getSelection) {
     var range = document.createRange();
     range.selectNode(document.getElementById(objId));
     window.getSelection().addRange(range);
     }
    }

    function fnDeSelect() {
     if (document.selection) document.selection.empty(); 
     else if (window.getSelection)
                window.getSelection().removeAllRanges();
    }
    </script>
<body>

<div id="test1">
    <p>jhsdgfhlsdlfkjsdklgjs</p>
    <p>jhsdgfhlsdlfkjsdklgjs</p>
    <p>jhsdgfhlsdlfkjsdklgjs</p>
</div>
<div id="test2">
    <p>jhsdgfhlsdlfkjsdklgjs</p>
    <p>jhsdgfhlsdlfkjsdklgjs</p>
    <p>jhsdgfhlsdlfkjsdklgjs</p>
</div>
<a href="javascript:fnSelect('test1');">Select 1</a>
<a href="javascript:fnSelect('test2');">Select 2</a>
<a href="javascript:fnDeSelect();">DeSelect</a>
</body>
Flavius Stef
Had to try it. Worked perfectly. +1
Stefan