Can I select any text using Javascript except for a text field and input text element?

Using Javascript, it is easy to programmatically select text inside a text field or text input element. What about

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

Can I use JavaScript to select the words "fast brown fox"? Or select the whole offer?

+3
source share
4 answers

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>
+5
source

You will need a way to manage the tag span. For example, idbut then in javascript I will edit some of the properties style. You can have a property for everything you want to highlight, as shown below.

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

, .

DocumentgetElementsByTagName("title")

Document.getElementByID("ID") . setAttribute(name, value) .

, .

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

css .highlight

.highlight{
  background-color:yellow;
}

javascript .highlight ,

<getSpanElement>.className='highlight';

, .

0

? , , .

... ! CSS span, .

: . , , .

0

Source: https://habr.com/ru/post/1709333/


All Articles