I would like to get HTML of an editable div. It contains text and an <input> tag. See:
document.body.addEventListener('click', () => {
console.log(document.getElementById('content').innerHTML);
})
body {
height: 100vh;
}
<div id="content" contentEditable="true">
I want <input type="number" value="3"> candies.
</div>
My problem is <input type="number" value="3">. When I update the value of the input field, I still get the default value.
So how can I get the live value of the input field?
I am not NOT looking for the value of the input field. The output should be the full content of div#content as a string.
>Solution :
Changing the value of an input doesn’t affect the value attribute in the HTML, because that’s used for its default value, not the current value.
You’ll need to merge the value of the input into the innerHTML of the DIV to get the result you want.
document.body.addEventListener('click', () => {
let html = document.getElementById("content").innerHTML;
let value = document.getElementById('input').value;
new_html = html.replace(/value="\d+"/, `value="${value}"`);
console.log(new_html);
})
body {
height: 100vh;
}
<div id="content" contentEditable="true">
I want <input type="number" value="3" id="input"> candies.
</div>