jon
jon

Reputation: 5

selecting the 1st element in a series of elements with class attribute

I am building a chrome extension and I need to be able to execute a click() on the first table with class show_review. The issue I have is that these links all have the same class with no ID.

Here is what I am trying to click there are multiple tables all with the same class:

<table cellpadding="0" cellspacing="0" class="show_review" onmousemove="csmd1(this)" onmousedown="csmd2(this)" onclick="adOpen(this,1,317543,'680536')" msm="1" msc="1"></table>

Here is my code. It doesn't do anything when I reload. Just sits there no click has been made.

if ($(".show_review")[0].length){
    $(".show_review")[0].click();
}

Upvotes: 0

Views: 55

Answers (2)

gdoron
gdoron

Reputation: 150253

if ($(".show_review").length){
    $(".show_review").eq(0).click();
}

Though you can do it with one line:

$(".show_review:first").click();

jQuery selectors and functions was designed to work with 0+ elements.
So in this case if no element was selected, the click function will just do nothing.

Thanks you jQuery!


Update: You might need to use the DOM ready event.

$(function(){
    ...
    $(".show_review:first").click();        
    ...
});

Upvotes: 2

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

var firstTable = $("table.show_review:eq(0)");

Upvotes: 1

Related Questions