Hugolpz
Hugolpz

Reputation: 18248

JQuery: Among selected elements, select nth element

Given HTML such as :

<div>
  <span>Hello</span>
  <p class="selected">Hello Again</p>
  <div class="selected">And Again</div>
  <p>And One Last Time</p>
</div>

And JS such as :

$( "div" ).children( ".selected" )[0].css( "color", "blue" ); // this doesn't work

It doesn't grab the first selected element. How to make it work ?

Note: it's for a loop, so I will have access to a var i.

https://jsfiddle.net/kg20avn5/

Upvotes: 0

Views: 51

Answers (4)

Sandip Patel
Sandip Patel

Reputation: 176

first of all you can not add html tags within p tag. As a rule you can not use block elements within p tag such as "div" , "p" tags however you can only use inline elements like "span", "strong" etc..

if you try to use block elements within your p tag javascript or jquery would behave weirdly.

check your html code syntax you must be getting red line

Upvotes: 1

j08691
j08691

Reputation: 207901

Each jQuery object also masquerades as an array, so when you use

.children( ".selected" )[0].css( "color", "blue" )

you're derfeferencing the jQuery object and getting the native DOM element. The problem with that is then you're trying to use a jQuery method (.css()) on it, which is why it fails.

To select the first match of something in jQuery you would typically use .eq(0), :eq(0), or :first

Example 1

$( "div" ).children( ".selected:first" ).css( "color", "blue" );
  body {
    font-size: 16px;
    font-weight: bolder;
  }
  p { margin: 5px 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>Hello</span>
  <p class="selected">Hello Again</p>
  <div class="selected">And Again</div>
  <p>And One Last Time</p>
</div>

Example 2

$( "div" ).children( ".selected:eq(0)" ).css( "color", "blue" );
body {
    font-size: 16px;
    font-weight: bolder;
  }
  p { margin: 5px 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>Hello</span>
  <p class="selected">Hello Again</p>
  <div class="selected">And Again</div>
  <p>And One Last Time</p>
</div>

Example 3

$( "div" ).children( ".selected" ).eq(0).css( "color", "blue" );
body {
    font-size: 16px;
    font-weight: bolder;
  }
  p { margin: 5px 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>Hello</span>
  <p class="selected">Hello Again</p>
  <div class="selected">And Again</div>
  <p>And One Last Time</p>
</div>

Upvotes: 1

Mojtaba
Mojtaba

Reputation: 5004

$( "div" ).children(".selected").first().css( "color", "blue" ); // this works

Upvotes: 2

Richard Hamilton
Richard Hamilton

Reputation: 26434

Use .eq

$("div").children(".selected").eq(0).css("color", "blue");

or

$("div").children(".selected:eq(0)").css("color", "blue");

Upvotes: 1

Related Questions