canacast
canacast

Reputation: 241

Need a more elegant way of finding an element in the dom tree with jQuery

I have a few elements flying around in an element that need to be altered when the window finishes loading ($(window).load...)

When the script loads, I've been struggling to find a more elegant way of finding a string.

Noticeably below, you can also see the rampant re-use of parent and next operators...

I've tried closest but it only goes up the dom tree once (from what I understand) and parents has never really worked for me, but I could be using it wrong.

Ex.

$(window).load( function(){
    if($(".postmetadata:contains('Vancity Buzz')").length){
        $(this).parent().parent().next().next().next().next('.articleImageThumb img').hide();
    }
});

HTML output this runs through looks like this:

<div class="boxy">
    <div class="read">  
        <div class="postmetadata">Vancity Buzz</div>
        <div class="articleTitle"></div>
    </div>
    <div class="rightCtrls"></div>
    <div class="initialPostLoad"></div>
    <div class="ajaxBoxLoadSource"></div>
    <div class="articleImageThumb">
        <a href="#">
            <img src="image.png" class="attachment-large wp-post-image" alt=""/>
        </a>
    </div>
</div>

Upvotes: 1

Views: 107

Answers (3)

wirey00
wirey00

Reputation: 33661

You can just do this

$('.articleImageThumb img').toggle($(".postmetadata:contains('Vancity Buzz')").length)

If there are multiple divs and you do need to traverse then there are multiple ways

$(".boxy:has(.postmetadata:contains('Vancity Buzz'))").find('.articleImageThumb img').hide()

or

$('.postmetadata:contains("Vancity Buzz")').closest('.boxy').find('.articleImageThumb img').hide()

or

$(".boxy:has(.postmetadata:contains('Vancity Buzz')) .articleImageThumb img").hide()

Upvotes: 4

PSL
PSL

Reputation: 123739

I think you want to do this:

$(".postmetadata:contains('Vancity Buzz')")
     .closest('.read') //Closest will get you to the parent with class .read
     .siblings('.articleImageThumb').hide(); //this will get you all the siblings with class articleImageThumb

this refers to window there not the element you are checking in the if condition.

Fiddle

I don't know if your intention is to have the empty anchor tag just by hiding the image. if so just add a find to it.

Upvotes: 6

ctatro85
ctatro85

Reputation: 311

Have you looked into parents http://api.jquery.com/parents/ you can pass a selector like so:

 $(this).parents('.boxy').find(".articleImageThumb")

Careful though, If there is a parent boxy to that boxy, parents() will return it and thus you find multiple .articleImageThumb.

Upvotes: 1

Related Questions