Content.select() Not Working On A Element
I'm trying to make a button to select the contents of a
element. However, it's not working and I am getting 'content.select() is not a function Solution 1:
You can actually solve this using Document.createRange()
, Range.selectNodeContents()
and Window.getSelection()
thus avoiding unnecessary DOM manipulation.
See the example on MDN or discussion in this question: Selecting text in an element (akin to highlighting with your mouse)
functioncopyConfig() {
const contentNode = document.getElementById("contentCfg")
const range = document.createRange();
range.selectNodeContents(contentNode);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("copy");
}
const copyButton = document.getElementById('copyButton');
copyButton.addEventListener('click', copyConfig);
<div><buttontype="button"id="copyButton"class="btn btn-primary">Copy Config</button><br><br><pre><codeid="contentCfg">{{ content }}</code></pre></div>
Solution 2:
Ended up fixing it by changing the js to this (added the elem parts)
functioncopyConfig() {
const content = document.getElementById("contentCfg").textContent;
const elem = document.createElement("textarea");
document.body.appendChild(elem)
elem.value = content;
elem.select();
elem.setSelectionRange(0, 99999);
document.execCommand("copy");
document.body.removeChild(elem);
}
Post a Comment for "Content.select() Not Working On A
Element"