morne
morne

Reputation: 4189

find id by traversing up to class

I want to find the id of the following.

    <div class="row" id="I_WANT_TO_FIND_THIS_CLASS">
        <div class="cell100">
            <div class="table">
                <div class="cell40 content label bordersRight borderBottom"><input class="inputField input270" type="text" name="Source1" value=""></div>
                <div class="cell15 content label bordersRight borderBottom"><input class="inputField input95" type="text" name="Date1" value=""></div>
                <div class="cell45 content label borderBottom"><input class="inputField input305" type="text" name="Result1" value=""></div>
                <div class="cell45 content label borderBottom"><INPUT type="button" value="x" onclick="removeRow(this)" /></div>
            </div>
        </div>
    </div>

this is my code that I tried. ( eventualy I want to delete the selected "row)"
There is a removeRow(this) button call on the 4th cell of the div

    function removeRow() {
        //$(this).closest('.row').remove();
        var div_id = $(this).closest('.row').attr('id');
        alert(div_id);
    }

Upvotes: 1

Views: 56

Answers (3)

rrk
rrk

Reputation: 15846

You are using jQuery. Try this.

$('input[type=button]').click(function(){
    div_id = $(this).closest('.row').attr('id');
    console.log($(this).closest('.row').attr('id'));
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You are passing the clicked element reference as a parameter so change the method syntax to accept the parameter and then use that to find the row element

function removeRow(el) {
    //$(this).closest('.row').remove();
    var div_id = $(el).closest('.row').attr('id');
    alert(div_id);
}

Note: Since you are using jQuery, use jQuery event handlers instead of inline handlers

Upvotes: 3

Adil
Adil

Reputation: 148120

You need object that is passed to removeRow, add parameter to removeRow, I added with name source. Use this source object instead of this.

Live demo

function removeRow(source) {
     //$(this).closest('.row').remove();
     var div_id = $(source).closest('.row').attr('id');
     alert(div_id);
}

Upvotes: 1

Related Questions