Select the contents of an element

suggest change

getSelection 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);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents