Bob Horn
Bob Horn

Reputation: 34325

Set Focus to Control With No Name or ID

I'd like to automatically set the focus on the input control within Angular's ui-grid filter:

enter image description here

However, that control doesn't have a name or ID. This is what the HTML looks like:

<div class="gridFullThin" ui-grid="gridApps" ui-grid-selection ui-grid-resize-columns></div>

I tried adding this attribute, but it didn't help:

autofocus="autofocus"

In IE, within the F12 tools DOM Explorer, I can see that the input looks like this:

<input class="ui-grid-filter-input ui-grid-filter-input-0 ng-touched" aria-label="Filter for column" type="text" placeholder="" ng-attr-placeholder="{{colFilter.placeholder || ''}}" ng-model="colFilter.term">

It doesn't have an ID. Is there a way I can automatically place focus here?

** EDIT ** - This is the generated HTML as shown in F12 (with the input element highlighted in blue):

enter image description here

Upvotes: 3

Views: 2721

Answers (2)

Serg Chernata
Serg Chernata

Reputation: 12400

Assuming you can't edit the markup to add your own ID, you can still target by class or specifying the input as a child of parent with id.

Correct answer as discussed in chat:

var elements = document.querySelector('.modal .ui-grid-header-cell .ui-grid-filter-input-0'); 
elements.focus();

Upvotes: 1

Russell Jonakin
Russell Jonakin

Reputation: 2006

if this is the first input element in your HTML mark-up, then you could do this:

document.forms[0].elements[0].focus();

otherwise, if you have hidden elements that come before this input, then you would have to loop throught the form elements and find the first non-hidden element.

Upvotes: 0

Related Questions