Home > OS >  Javascript focus on span that is inside a div
Javascript focus on span that is inside a div

Time:09-22

div {
  border: 3px solid black;
}

span {
  border: 2px solid blue;
}
<div contenteditable>
  <span contenteditable id="haha"><i>asd</i></span>
</div>

I want to focus on #haha, but it only works if I move the element outside the div

div {
  border: 3px solid black;
}

span {
  border: 2px solid blue;
}
<div contenteditable>

</div>
<span contenteditable id="haha"><i>asd</i></span>

Currently using this this code for the focus, if there a way to focus on the span element even if it's inside the div?

document.querySelector(`#haha`).focus();

CodePudding user response:

Try document.getElementById("haha") (notice I removed the '#')

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

Source

EDIT:

Looks like manipulating the tabindex allows this to work:

myFunction = function() {

  let x = document.getElementById("haha");
  x.setAttribute('tabindex', '0');
  x.focus();
}

myFunction();
<div contenteditable>
  <span contenteditable="true" id="haha">asd</span>
</div>
<button class="bold">Bold</button>

<div contenteditable="true">
  whatever
</div>

<button class="bold">Bold</button>

CodePudding user response:

Try setting tabindex="0". It allows items which normally are not focusable to receive focus

    
div {
  border: 3px solid black;
}

span {
  border: 2px solid blue;
}
span:focus{
border-color: green;
}
<div contenteditable>
  <span tabindex="0" contenteditable id="haha"><i>asd</i></span>
</div>

CodePudding user response:

You need to add some text into the div. Then they'll each have their own content to edit.

div[contenteditable] {
  border: 3px solid black;
}

span {
  border: 2px solid blue;
}
<div contenteditable>div<span contenteditable id="haha">span</span></div>

  • Related