Manoj Singh
Manoj Singh

Reputation: 7707

how to get the DIV ID from given HTML in JQuery

I have below HTML format:

<ul class="whatlike-list">
    <li class="first">
        <a href="/SessionHandler.aspx" class="button-flight-search">Search for Flights</a>
        <div class="open-block-holder">
            <div id="slideFlightSearch" class="open-block" style="display: block; left: 650px;">

            </div>
        </div>
    </li>
</ul>

Now I am looking to get DIV ID="slideFlightSearch" on the click of link "Search for Flights", I have got the class "button-flight-search" in my $this object. Something like below in my JQuery.

$(link).click(function()
{
    alert($(this).attr("class"));
})

In the above alert I am getting the class "button-flight-search", however I need the inner DIV ID slideFlightSearch

Please suggest using JQuery.

Upvotes: 2

Views: 1380

Answers (3)

Gan
Gan

Reputation: 4967

A method using your HTML structure without using ID or class attributes.

$(link).click(function()
{
    alert($(this).next()         //get div with class "open-block-holder".
                 .children()     //get the inner div with class "open-block".
                 .attr("id") ) ; //get the ID.

})

Upvotes: 0

David Thomas
David Thomas

Reputation: 253506

You could try:

$('a').click(
    function(){
        var theDivID = $(this).closest('li').find('.open-block').attr('id');
        alert('The div's ID is: ' + theDivID);
        return false; // If you need to prevent the default action of clicking on a link.
    });

Upvotes: 1

karim79
karim79

Reputation: 342795

You can use .next and .find, like this:

$(link).click(function() {
    var id = $(this).next(".open-block-holder")
                    .find("div") // or .find("div.open-block")
                    .attr("id");
});

Upvotes: 2

Related Questions