1

I want to change first li test, but it is giving me typeerror

$("li")[0].css("color", "orange");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>Candy</li>
  <li>Fruits</li>
  <li>Chocolate</li>
</ul>

5
  • You can use .eq(0) to get the jQuery object Commented Jul 26, 2020 at 13:30
  • Okay! but why downvote ? Commented Jul 26, 2020 at 13:34
  • $("li")[0] also gives first element, then why can't I use .css() API on $("li")[0] Commented Jul 26, 2020 at 13:41
  • Because $("li")[0] returns a native HTML element. See my answer for the code example :) Commented Jul 26, 2020 at 13:43
  • $("li")[0] returns the native <li> element which would be identical to document.querySelector('li') BUT native elements don't have a css() method, that is a jQuery object method Commented Jul 26, 2020 at 13:43

3 Answers 3

4

JQuery uses its own structures, so you cannot use square brackets to get the first element and then keep using JQuery instructions as it returns a native HTML element.

You should use .first() instead to get the first element (or .eq(i) to the the i element)

$("li").first().css("color", "orange");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>Candy</li>
  <li>Fruits</li>
  <li>Chocolate</li>
</ul>

If you want to mix JQuery with native HTML (not recommended) you could with this:

$("li")[0].style.color = "orange";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>Candy</li>
  <li>Fruits</li>
  <li>Chocolate</li>
</ul>

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

1 Comment

Your first statement is very misleading as $(selector)[0] does indeed return a native element assuming there is a matching selector
0

Try with below, please specify 1,2,3,... n number to select specific li element

$( "ul li:nth-child(1)" ).css("color", "orange");

Comments

-1

This will work...

 var item2 = $( "li.item-2" );
 $( "ul" ).find( item2 ).css( "background-color", "red" );
<ul>
    <li class="item-1">Candy</li>
    <li class="item-2">Fruits</li>
    <li class="item-3">Chocolate</li>
</ul>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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.