Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
Javascript focus on span that is inside a div

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();
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!