0

I have a question about the javascript. I write a function in the javascript and I write the function in .html file.

However, when I click the button, it shows the 'Object doesn't support this property or method' error in IE 8.

Can anyone help me? Thank you.

function colour (colour) {
    var selectTxt =    
       window.getSelection() ||
       document.getSelection() ||
       (document.selection ? document.selection.createRange().text : ''),
       targetHTML = document.getElementById('text'); // text is a id in HTML
       targetHTML.innerHTML =
         targetHTML.innerHTML.replace(
                  RegExp(selectTxt),
                  '<span class="' + colour + '">'+selectTxt+'</span>');
}

// HTML
<input type="button" onclick="colour('green')" value="Green"/>
<p id='text'>I live in ABC and I am working in ABC company.</p>

1 Answer 1

5

You're executing the methods before checking if they exist, so when such method is not supported (e.g. window.getSelection) you'll indeed get error.

Add such function to your code:

function GetSelectedText() {
    if (window.getSelection)
        return window.getSelection();
    if (document.getSelection)
        return document.getSelection();
    if (document.selection)
        return document.selection.createRange().text;
    return "";
}

Then simply have:

var selectTxt =  GetSelectedText();
Sign up to request clarification or add additional context in comments.

1 Comment

Something John should read: Introduction to Range

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.