Given a div with contenteditable=true
, how can I add text to the element?
<div aria-autoplete="list" contenteditable="true" role="textbox" spellcheck="true">
</div>
I've tried document.activeElement.value
, but since it's a div I can't set the value
Given a div with contenteditable=true
, how can I add text to the element?
<div aria-autoplete="list" contenteditable="true" role="textbox" spellcheck="true">
</div>
I've tried document.activeElement.value
, but since it's a div I can't set the value
- 1 You have to use the innerHTML method. element.innerHTML = "content" ; For further information look to the doc. developer.mozilla/fr/docs/Web/API/Element/innertHTML – Nico Commented Nov 7, 2018 at 14:25
4 Answers
Reset to default 2With the other answers about innerHTML
, I am afraid if innerHTML
without sanitization might give attackers a chance to run unwanted malicious code.
I would rather go with textContent
because the OP wants to add text.
HTML:
<div id="content" aria-autoplete="list" contenteditable="true" role="textbox" spellcheck="true">
</div>
JAVASCRIPT:
document.getElementById('content').textContent = 'My text';
If you want to render HTML tags too you need a sanitization callback to filter tags like SCRIPT tag as an example.
You can just change the innerHTML of the div. So for example:
document.activeElement.innerHTML = "Changed text";
You can also get the current contents of the div by getting the same property, for example:
alert("User entered text: " + document.activeElement.innerHTML);
A React ref version answer of this question:
// set the init value to it
const initText = "123\n123123\n123123123";
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (ref && ref.current) {
ref.current.innerText = initText;
}
}, []);
const handleInput = (e: ChangeEvent<HTMLDivElement>) => {
console.log("input:", e.target.innerText);
};
notice that we are using innerText
here,
for innerHtml
, textContent
they won't give a default line-change for \n
with the code below
<div
ref={ref}
contentEditable={true}
onInput={handleInput}
style={{
height: 200,
width: 200,
border: "1px solid black",
display: "table-cell",
verticalAlign: "middle",
textAlign: "left",
padding: 8
}}
></div>
additionally, we can use CSS :empty
to let the initial cursor keep at the vertical center as well
.InputField {
height: 200px; // initial height, real size could auto increase
...
}
.InputField:empty {
line-height: 200px; // the same initial height's value as above
}
I've found that the best way to set the content is:
target.firstChild.data = "<some-new-value>";
..where the firstChild is the textNode.