Frank
Frank

Reputation:

jQuery hierarchy issue with next()

Seems like $("img").next().hide(); is not working when both the image and div tag are a child of a paragraph.

<p>
<img src="image.jpg" />
<div>text</div> // this div is set to 'display: none' by default in css
</p>

Yet, if I substitute <div> with <span>

<p>
<img src="image.jpg" />
<span>text</span>
</p>

or if I omit the <p> tags

<img src="image.jpg" />
<div>text</div>

the jQuery selector does work properly. Any ideas why this is the case? Is it related to inline and block display? How can I make it work as described in the top code example?

This is the jQuery code I am using:

$(document).ready(function(){
    $("img").hover(
        function()
        {
            $(this).next().show();
        },
        function()
        {
            $(this).next().hide();
        }
    );
});

Thanks for your help!

Upvotes: 0

Views: 241

Answers (2)

Gumbo
Gumbo

Reputation: 655349

The p element does only allow inline-level elements as child elements. This may be the reason for why your first example does not work.

Upvotes: 0

Thinker
Thinker

Reputation: 14464

You should not use block element (DIV) inside inline elmenents (P). Instead of P use DIV with class set like P.

Upvotes: 1

Related Questions