mister martin
mister martin

Reputation: 6252

JQuery trouble accessing next of target element

JSFiddle

I can't figure out why, but if in the fiddle above if you type any character into the input followed by the down key, the console makes two logs. The first is a value of 3 (correct) and the second is a value of 0 (incorrect).

I'm trying to target the element following a specific input:

// this works...
console.log($('.autocomplete li').length);
// this does not work
console.log($(this).next('.autocomplete li').length);

If I just log $(this) it returns input as expected. I've also tried .nextAll, .find and various combinations.

Why isn't it finding the .next element of the target?

Upvotes: 1

Views: 32

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

It is the .autocomplete that is next to this, not the li. So the filter will not work.

Instead, you would need to use $(this).next('.autocomplete').find('li')

However, have you considered a JS-free solution?

<input type="text" list="options" />
<datalist id="options"> <!-- ^-- Same identifier -->
  <option>America</option>
  <option>Europe</option>
  <option>Japan</option>
</datalist>

Upvotes: 3

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

This works fine:

console.log($(this).next('.autocomplete').find('li').length);

You need to target the next .autocomplete and find the li.

Upvotes: 1

Related Questions