Yulian
Yulian

Reputation: 6759

How can I loop through all elements of a certain type through jQuery?

There are some similar questions, but mine is a little bit more specific.

I have a table element with an id of "myTable" and some tr elements inside it (let's say the tr elements are 2).

<table id="myTable">
    <tr>
        <td>Row 1</td>
    </tr>
    <tr>
        <td>Row 2</td>
    </tr>
</table>

If I try to see the number of rows in the #myTable table element, by writing

var numberOfRows = $("#myTable tr").length;

I always have 1 in the numberOfRows variable.

It only works when I add a class to all the tr elements.

 <table id="myTable">
    <tr class="myRows">
        <td>Row 1</td>
    </tr>
    <tr class="myRows">
        <td>Row 2</td>
    </tr>
</table>

Let's say the class is "myRows" and write the following:

var numberOfRows = $("#myTable .myRows").length;

Then, I get the right number - 2.

So, my question is how can I get the number of certain elements or loop through them if they are not distinguished by a class (like in the example above)?

Upvotes: 1

Views: 650

Answers (2)

Bellash
Bellash

Reputation: 8184

Pure JavaScript that also works in all meyor browsers

 var rows=document.getElementById("myTable").rows;
 for(var rowIndex=0;rowIndex<rows.lenght;rowIndex++){
        //now do everything with tr $(rows[rowIndex]).height(80)
 }

Upvotes: 0

Gyani
Gyani

Reputation: 2241

you can use like :

$('#myTable > tbody  > tr').each(function() {...code...});

Upvotes: 1

Related Questions