Nick Grealy Nick Grealy - 2 months ago 9
jQuery Question

Jquery selector > can't select autofocus attribute

I want to select elements that have an

autofocus
attribute present. For some reason, my jquery selector
$("[autofocus]")
isn't returning anything.

I imagine this is a simple solution, I just can't see what I'm doing wrong (is it a bug?!).

Browser: Chrome - Version 52.0.2743.116 m (64-bit)

HTML :



<input id="a" type="text" autofocus="autofocus" value="a" />
<input id="b" type="text" autofocus="autofocus" value="b" />
<input id="c" type="text" autofocus="autofocus" value="c" />


Javascript :



console.log($("[type=text]").length); // -> 3
console.log($("[autofocus]").length); // -> 0
console.log($("[autofocus=autofocus]").length); // -> 0


Why can't I select the
autofocus
attribute?

JSBin


Answer

Working fiddle

Your code works just fine as you could see in the example below. the bug come from the JsBin that translate the autofocus="autofocus" to ="autofocus".

Hope this helps.

var focusFn = function(){
  console.log("inside fn");
  console.log($("[type=text]").length);
  console.log($("[autofocus]").length);
  console.log($("[autofocus=autofocus]").length);
  $("input[type=text]:visible:first").focus();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="focus" onclick="focusFn()"></input><br/>
<input id="a" type="text" autofocus="autofocus" value="a" /><br/>
<input id="b" type="text" autofocus="autofocus" value="b" /><br/>
<input id="c" type="text" autofocus="autofocus" value="c" /><br/>