Select the contents of an element
suggest changegetSelection can return null, and getElementById returns null when the id is missing. Most browsers keep a single range, so clear the old selection before adding one.
const sel = document.getSelection();
const myNode = document.getElementById("element-to-select");
if (sel && myNode) {
const range = document.createRange();
range.selectNodeContents(myNode);
sel.removeAllRanges();
sel.addRange(range);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents