Algorithm
Algorithm

Reputation: 329

How to select an element?

Why this code does not work? And is there another way to select the first item?

<div>
    <a href="#">text</a>
    <a href="#">text</a>
</div>

<script type="text/javascript">
$(function() {
     $('div a').each(function(){
          $(':first', this).css('color', 'red');
         //...other actions with $(this)
     });
});
</script>

I know that i can select an element like this: $('div a:first')

Upvotes: 2

Views: 123

Answers (4)

Jost
Jost

Reputation: 368

Maybe this is what you want

<div>
    <a href="#">text</a>
    <a href="#">text</a>
</div>

<script type="text/javascript">
    $(function() {
        $('div a').each(function(i, elm){
            if (i == 0){
                $(elm).css('color', 'red');
            }                             
            //...other actions with $(this)
        });
    });
</script>

Upvotes: 1

user113716
user113716

Reputation: 322452

These will work.

$('div a').first();
$('div a').eq(0);
$('div a').slice(0,1);
$('div a').filter(':first');

If you only want the first, no sense looping.

If you will need the rest of them for some purpose, cache the result of the selector, the pull the one(s) you need.

var $div_a = $('div a');

$div_a.first(); // for the first
$div_a.slice(1,4); // for the second through fourth

Upvotes: 2

Jman
Jman

Reputation: 936

$(function() {
     $('div a').each(function(index){
          if(index === 0){
               $(this).css('color', 'red');
          }
         //...other actions with $(this)
     });
});

Upvotes: 1

Neil
Neil

Reputation: 5782

Inside an each loop, $(this) is the object you're looking for. You don't need to do any further selection unless you're searching for something inside of $(this). If you're trying to highlight the first, you should do it outside a call to each because it doesn't make much sense calling it n times.

Upvotes: 1

Related Questions