0

I want to dynamically insert childnode in cursor position and set focus

var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var span = document.createElement("span");
span.id= 'ttt';
span.style.color = "red";
span.appendChild(selectionContents);
span.innerText = 'dfdf';
range.insertNode(span);

i can set node focus, but chileNode can't

dom.focus();//OK
dom.lastElementChild.focus();//can't  

log lastElementChild i can see the span and id='ttt'.....

teobais
  • 2,820
  • 1
  • 24
  • 36
Mazs Li
  • 161
  • 6

2 Answers2

0

Use window.location.hash = '#ttt';

This will scroll to the element

0

As I have already commented, span does not have focus event. Following is a SO Post - Which HTML elements can receive focus? for reference.

To answer your question, you can try adding a textbox with readonly property and add proper css to mimic it as label.

Fiddle

Edit 1

I have added css in :focus. You should create a class and toggle this class.

Code

function focusDiv() {
  document.getElementById("divTT").focus();
}

function focusSpan() {
  document.getElementById("lblTT").focus();
}

function focusText() {
  document.getElementById("txtTT").focus();
}
div:focus{
  background:blue;
}
span:focus{
  background:blue;
}
input:focus{
  background:blue;
  font-size:20px;
  font-family:Gorgia;
  color:#eee;
}

.label{
  border:0px;
}
<div id="test">Test
  <br/>
  <span id="lblTT">Span</span>
  <br/>
  <div id="divTT">Div</div>
  <input type="text" id="txtTT" class="label" value="Text" readonly>
</div>
<button onclick="focusSpan()">Focus Span</button>
<button onclick="focusDiv()">Focus Div</button>
<button onclick="focusText()">Focus Text</button>
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • Thank you!! but i want add a span or div or font when i click some button `
    dddddd
    ` => `
    dddddd
    ` then set focus in font , when user continued input after click button , input will change font size and color , what can I do? thanks
    – Mazs Li Dec 11 '15 at 08:55