1

I am writing very basic html and wanted to select only one element using css selector. However, the query returns one element in an array. I can access my element by indexing the array with [0] but is there a way to modify the query to return my element only?

<input class='myInput' id='myId'>

Css Selector:

'input.myInput'

When used in Chrome dev console, I see:

[<input class='myInput' id='myId'>]

instead of:

<input class='myInput' id='myId'>
3
  • Should this be tagged jQuery too? Commented Jul 6, 2013 at 1:37
  • @BjornJohnson: I dunno. It's not clear whether he's using the native API or jQuery to select elements. Commented Jul 7, 2013 at 5:25
  • Yeah. I was more or less asking him. I should have just said "Are you using jQuery?" :) Commented Jul 7, 2013 at 11:15

2 Answers 2

3

You can use the querySelector() method, which always returns the first element from a query:

var element = document.querySelector('input.myInput');

jQuery doesn't have a direct equivalent so you have to use the [0] index for that.

Sign up to request clarification or add additional context in comments.

Comments

2

jQuery returns queries with a jQuery Object, which is an array of the returned objects. So to get the line that you are looking for <input class="myInput" id="myId"> what you need to do is $('input.myInput')[0]; which gets the 0th element in the array, in this case there is only one, but to get the HTML element you need the [0] after the selector query.

Just an FYI on ther ways to get the same input:

$('.myInput')[0];
$('#myId')[0];
$('input')[0];

Or any of the above selectors with .first() after instead of [0] because they both grab the first element in the returned jQuery Object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.