Unde" /> Unde" /> Unde"/>

Focus Nearest Div of Select Element

1.6k views Asked by At

I have select element

  <select id="tokenize" multiple="multiple" 
class="tokenize" style="margin: 0px;
 padding: 0px; border: 0px; display: none;"/>

Under select element there is div with it is class

<div class="tokenize Tokenize">
<ul class="TokensContainer ui-sortable">
<li class="Placeholder" style="display: list-item;">
enter Position</li><li class="TokenSearch">
<input size="5"></li></ul><ul class="Dropdown"
 style="display: none;"></ul></div>

I want to focus(with cursor) that div which is nearest to select.That div created dynamically via javascript so I can not fix it from html so I try javascript.I want to focus div(it is class tokenize) which is nearest select element(it is id tokenize)

I try this but this not work

  document.getElementById(Select-Element-ID).firstElementChild.focus().select();
2

There are 2 answers

4
giggi__ On BEST ANSWER

You have to add the tabindex attribute to the div to make it focusable.
Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex

UPDATE:

var $inputToFocus = document.getElementById(Select-Element-ID).nextElementSibling.querySelector('.TokenSearch input');

$inputToFocus.focus();
0
Rahul khanvani On

This is the most advanced solution of your problem using Jquery.. and yet very simple

$("#tokenize").closest("div").focus();