Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
83
rated 0 times [  89] [ 6]  / answers: 1 / hits: 21871  / 14 Years ago, sat, march 5, 2011, 12:00:00

it has any way for bind execcommand with a div element not for whole document , i try this :



document.getElementById('div').execcommand(...)


but it has an error :



execcommand is not a function


it has any way for bind the execcommand with just div element not whole document !!
i don't like use iframe method .


More From » execcommand

 Answers
47

This is easier to do in IE than other browsers because IE's TextRange objects have an execCommand() method, meaning that a command can be executed on a section of the document without needing to change the selection and temporarily enable designMode (which is what you have to do in other browsers). Here's a function to do what you want cleanly:



function execCommandOnElement(el, commandName, value) {
if (typeof value == undefined) {
value = null;
}

if (typeof window.getSelection != undefined) {
// Non-IE case
var sel = window.getSelection();

// Save the current selection
var savedRanges = [];
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
savedRanges[i] = sel.getRangeAt(i).cloneRange();
}

// Temporarily enable designMode so that
// document.execCommand() will work
document.designMode = on;

// Select the element's content
sel = window.getSelection();
var range = document.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);

// Execute the command
document.execCommand(commandName, false, value);

// Disable designMode
document.designMode = off;

// Restore the previous selection
sel = window.getSelection();
sel.removeAllRanges();
for (var i = 0, len = savedRanges.length; i < len; ++i) {
sel.addRange(savedRanges[i]);
}
} else if (typeof document.body.createTextRange != undefined) {
// IE case
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.execCommand(commandName, false, value);
}
}


Examples:



var testDiv = document.getElementById(test);
execCommandOnElement(testDiv, Bold);
execCommandOnElement(testDiv, ForeColor, red);

[#93415] Friday, March 4, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamronr

Total Points: 749
Total Questions: 110
Total Answers: 122

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
kamronr questions
Mon, Dec 21, 20, 00:00, 3 Years ago
Fri, Oct 16, 20, 00:00, 4 Years ago
Sat, Oct 3, 20, 00:00, 4 Years ago
Sun, Jul 28, 19, 00:00, 5 Years ago
;