Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select just the first one

My javascript

            $(".controls").click(function(event) {

                  var div = $(event.target).parents(".controls");

                  var a = $(div).find("tr .select");


            return false;
        });

And html

 <div id="grid1" class="controls">

    <a href="/projekt/create">Add</a>
    <a href="/projekt/edit">Edit</a>

</div>


<div id="grid2" class="controls">

    <a href="/uloha/create">Add</a>
    <a href="/uloha/edit">Edit</a>

    <table>
    <tr id="1"></tr>
    <tr id="2" class="select"></tr>
    <tr id="3"></tr>

    </table>

</div>

I'd like to select the first TR which has class select. I've tried

var a = $(div).find("tr:first .select");

or

var a = $(div).find("tr .select:first");

but none of them worked.

like image 489
user137348 Avatar asked Dec 31 '25 07:12

user137348


1 Answers

You could try this:

var a = $("tr.select", div).first();

or

var a = $("tr.select:first", div);

Since there's :first and first().

To select all of this within that you use:

$(this, that)

Would something like this work?

$(".controls").click(function(event) {
    var a = $("tr.select:first", ".controls");
    // do stuff with a....
    return false;
});

This changes "two" to okay, but not 'four" when you press the button.

<div class="controls">
    <input type="button" value="Click the control" />
</div>
<div id="grid2" class="controls">
    <table>
        <tr id="1"><td>one</td></tr>
        <tr id="2" class="select"><td>two</td></tr>
        <tr id="3"><td>three</td></tr>
        <tr id="4" class="select"><td>four</td></tr>
    </table>
</div>
<script type="text/javascript">
    $(".controls input").click(function(event) {
        var a = $("tr.select:first", ".controls");
        $(a).text("okay");
        return false;
    });
</script>

(As a side note, those are not proper id names, they cannot start with a number if you want valide html)

like image 125
Peter Ajtai Avatar answered Jan 01 '26 19:01

Peter Ajtai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!