I have a <div contenteditable=true>
where I define by a WYSIWYG some elements. For example <p>
,<h1>
, etc. I would like to put directly the focus on one of this elements.
For example on <p id="p_test">
. But it seems that focus()
function doesn't work on <div>
elements, <p>
elements...
Is there a another means to define the focus in my case?
Answer: Use the HTML5 contenteditable Attribute You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.
The contentEditable property of the HTMLElement interface specifies whether or not the element is editable. This enumerated attribute can have the following values: ' true ' indicates that the element is contenteditable . ' false ' indicates that the element cannot be edited.
moveToElementText(contentEditableElement);//Select the entire contents of the element with the range range. collapse(false);//collapse the range to the end point. false means collapse to end rather than the start range.
It is a default behavior of any element which have content-editable attributes set to true whenever, the element gets a focus it will get a border around them. The task can be done by using the [attribute] selector to select all elements that are contenteditable, and remove the border with the outline property.
Old post but none of the solutions worked for me. I figured it out eventually though:
var div = document.getElementById('contenteditablediv'); setTimeout(function() { div.focus(); }, 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With