Valeriane
Valeriane

Reputation: 954

jquery select (find) element

I have a table on my page html :

<table id="myTab">
    <tr>
        <td class="reference">1</td>
        <td>item1</td>
        <td>Info item - 1</td>
    </tr>
    <tr>
        <td class="reference">2</td>
        <td>item2</td>
        <td>Info item - 2</td>
    </tr>
    <tr>
        <td class="reference">3</td>
        <td>item3</td>
        <td>Info item - 3</td>
    </tr>
    <tr>
        <td class="reference">4</td>
        <td>item4</td>
        <td>Info item - 4</td>
    </tr>
<table>

How I can select an element of my table with class reference innerHtml value=3?

var el = $(myTab).find('???')

Upvotes: 0

Views: 185

Answers (3)

sohel khalifa
sohel khalifa

Reputation: 5588

Or a pure javascript:

 function func() {
        var myTab= document.getElementById('myTab');
        var len = myTab.rows.length;
        for (var r = 0; r < len; r++) {
            var rowLen = myTab.rows[r].cells.length;
            for (var cel = 0; cel < rowLen; cel++) {
                if(myTab.rows[r].cells[c].innerHTML === "3" && myTab.rows[r].cells[c].className === "reference")
                {
                   alert("found:"+myTab.rows[r].cells[c].innerHTML);
                }
            }
        }
    }

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150080

var el = $("#myTab").find("td.reference:contains(3)")

...will work assuming the :contains selector is good enough - noting that it matches on (in this case) "3" anywhere within the content of the element.

If you need an exact match you can use .filter():

var el = $("#myTab").find("td.reference")
                    .filter(function() { return $(this).html() === "3"; });

Upvotes: 2

James Allardice
James Allardice

Reputation: 166071

Assuming you want a reference to just that td element, and the markup you've shown is the extent of your current structure, you can use the :contains selector:

var elem = $(".reference:contains('3')");

If you have other td elements containing the character 3 (e.g. 13) they will also be matched. In that case, it's probably better to use the .filter() method:

var elem = $(".reference").filter(function () {
    return $(this).text() === "3";
});

Upvotes: 9

Related Questions