0

Lots available on this subject but I havn't found anything that answers my question... If you find this superfluous, please say so politely instead of berating me. I've tried really hard on this!

The goal is simple enough. I've got a series of divs, some of which contain anchors. I'm trying to compare the window's hash to the title attributes of the div's anchor children and then click the parent of the anchor who matches.

My function below logs the correct array of anchor children but I'm not seeing a click-result. I'm sure I'm missing something.

Thanks for the help.

<div class="box"><img src="#" /></div>
<div class="box"><a href="#" title="blah"><img src="#" /></a></div>
<div class="box"><img src="#" /></div>

if(window.location.hash) {
    var hash = window.location.hash.substring(1),
        box  = $('.box').children('a').each(function(){
                   $(this).attr('title');
               });

    if (box.attr('title') == hash) {
        $(this).parent().click();
    }
}

1 Answer 1

1

From what it looks like you're doing there, the $(this).attr('title') isn't doing anything - it is just returning a value, and nothing is being done with it.

If it were me, I would do it like this:

if(window.location.hash) {
    var hash = window.location.hash.substring(1),
        boxes = [];

    $('.box').children('a').each(function(){
        if ($(this).attr('title') == hash) {
            boxes.push(this); // OR:
            $(this).parents("div.box").click();
        }
    });

    // Or, you can iterate through your boxes array and perform more validation here.
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.