M22an
M22an

Reputation: 1292

Can we use a constructed dynamic jQuery selector?

I want to contruct a jquery selector as a string and pass its value to the selector.

$(document).on( 'keyup', function( e ) {
    if( e.keyCode == 9 ) {
        //console.log( e.target );

        console.log(e.target.id);

        var preTabIndex = document.getElementById(e.target.id).tabIndex;
        var nextTabIndex = preTabIndex + 1;

        console.log(preTabIndex);
        console.log(nextTabIndex);

        //console.log($('[tabindex=3]')[0].id);

        var selector = "[tabindex=" + nextTabIndex + "]";

        console.log(selector);
        console.log($(selector)[0].Id);

        //document.getElementById($("[tabindex=3]")[0].id).focus();
        document.getElementById($(selector)[0].id).focus();
    }
} );

Can this be done? I couldn't find it on my initial googling.

With this i am getting an undefined when i do

console.log($(selector)[0].Id);

Upvotes: 0

Views: 83

Answers (1)

Yosep Kim
Yosep Kim

Reputation: 2941

Yes, you can. Make sure you use the . or # to denote the target. For example,

In your HTML:

<p id="header">hello</p>

In your JS:

var my_selector = "#header";
$(my_selector).html('wow');

Upvotes: 1

Related Questions