nsilva
nsilva

Reputation: 5612

Find closest <a> link with jQuery

I have the following list:-

    <div id="main-links-bottom-hover">

        <div id="About" class="hovers">

            <div id="main-about-div">

                <li class="lnk1 about-lnk"><a href="contact.php">Contact</a></li>
                <li class="lnk2 about-lnk"><a href="technology.php">Technology</a></li>
                <li class="lnk3 about-lnk"><a href="environment.php">Environment</a></li>
                <li class="lnk4 about-lnk"><a href="terms.php">T&amp;C's</a></li>
                <li class="lnk5 about-lnk"><a href="pricing.php">Pricing Policy</a></li>

            </div>

        </div>

    </div>

For each <li> I want to set the li to open the closest <a href>.

I have tried:-

    $('li').each(function(){
        var linkitem = $('.lnk1 a', this).attr('href');
        $('a.lnk1', this).attr('href' , linkitem) 
    });

But this doesn't seem to be working, any suggestions?

ADDED CSS:-

#main-about-div {
    position:absolute;
    top:5px;
    left:5px;
}

.lnk1, .lnk2, .lnk3, .lnk4, .lnk5, .lnk6 {
    list-style-type: none;
    font-size:13px;
    margin-bottom:5px;
    margin-top:-5px;
    width:140px;
    height:30px;
    margin-left:-5px;
    cursor:pointer;
    border-bottom:1px dotted #1f5779;
}

.lnk1 a {
    position:absolute;
    top:-2px;
    left:5px;
    color:#FFF;
}

.lnk2 a {
    position:absolute;
    top:30px;
    left:5px;
    color:#FFF;
}

.lnk3 a {
    position:absolute;
    top:61px;
    left:5px;
    color:#FFF;
}

.lnk4 a {
    position:absolute;
    top:92px;
    left:5px;
    color:#FFF;
}

.lnk5 a {
    position:absolute;
    top:124px;
    left:5px;
    color:#FFF;
}

.lnk6 a {
    position:absolute;
    top:156px;
    left:5px;
    color:#FFF;
}

Upvotes: 0

Views: 967

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 185943

Do this:

#main-about-div a {
    display: block
}

Since your LI elements only contain one A element each, if you make the A elements block-level, they should take up the entire space of their parent LI element, and then clicking on the LI element will automatically mean that the corresponding A element is also clicked.


Update: After seeing your CSS code.

#main-about-div li {
    list-style-type: none;
    font-size:13px;
    border-bottom:1px dotted #1f5779;
}
#main-about-div a {
    display: block;
    width: 140px;
    height: 30px;
    background: pink;
}

Live demo: http://jsfiddle.net/simevidas/reSE8/ (uses normalized CSS)

Notice how the A elements are blocks now and the dimensions are set on them instead of the LI elements.

Upvotes: 12

srijan
srijan

Reputation: 1522

This may help!

$('li').each(function(){

    p = $(this).find('a');
    $(p).attr('href','Not sure what you are trying to do but your custom href goes here');
    
});

Upvotes: -1

Related Questions