Navin Rauniyar
Navin Rauniyar

Reputation: 10525

how to select closest class and its id with closest method

<div id="demo">
    <div class="moduletable">
        <div class="demo">
            <div class="demo-wrap">
                <div class="container" id="button-1">Button-1 contents</div>
                <div class="ctrl">
                    <div><a href="#buttton-1">Button-1</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

jQuery

$('ctrl').click(function(){

$(this).closest('.container #button-1').width();

// how to select the class container first and then its id that is button-1

}

Edit

<div class="container" id="button-1">Button-1 contents</div>
<div class="container" id="button-2">Button-2 contents</div>
<div class="ctrl">
<div><a href="#buttton-1">Button-1</a>
</div>
</div>

How can I get container width as its id if one button is pressed it should alert button-1 width and if another it should alert button-2.

Upvotes: 0

Views: 112

Answers (3)

Afsal
Afsal

Reputation: 349

Please try this

$('.ctrl').click(function(){
    alert($(this).prev(".container").attr('id'));
});

Jsfiddle link

To find the width:

$('.ctrl').click(function(){
    alert($(this).prev(".container").width());
});

Upvotes: 1

Neeraj
Neeraj

Reputation: 4489

Try

$(".ctrl").on("click",function(){
       alert($(this).parent().parent().find('.container').attr("id"));

Fiddle Demo

Hope it helps you

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78525

You can find it as the previous sibling:

$(this).prev(".container")

Then grab it's id:

$(this).prev(".container").prop("id");

edit: To get it's width:

$(this).prev(".container").width();

Upvotes: 0

Related Questions