Todd Davis
Todd Davis

Reputation: 6035

jQuery selector not working the way I'm expecting

Consider the following simple HTML:

<div id="navcontainer">
        <a href="#"><img alt="" src="Img1.jpg" /></a>
        <a href="#"><img alt="" src="Img2.jpg" /></a>
        <a href="#"><img alt="" src="Img3.jpg" /></a>
        <a href="#"><img alt="" src="Img4.jpg" /></a>
        <a href="#"><img alt="" src="Img5.jpg" /></a>
</div>

And for the sake of argument, let's say it's a very small portion of a large page with many DIV's and A's.

What I want to do is hide the tags and the images inside them. If I do this, it works:

$('a').hide();

But like I said, there are a lot of links on the page, so I want to be very specific. Essentially, I want ONLY the links that are inside a <div> with the class of "navcontainer". So from what I'm seeing on the web, it should be one of the following two formats. The second one looks perfect to me. But neither is working for me.

$('div.navcontainer a').hide();
$('div.navcontainer > a').hide();

I must be missing something stupid. Can anyone please clue me in?

Upvotes: 2

Views: 120

Answers (7)

Alnitak
Alnitak

Reputation: 340055

A dot prefix in a selector is for classes, but you've actually got an ID so you should use a hash prefix instead, e.g:

$('#navcontainer > a').hide();

It's far better not to put the div prefix on the selector - it'll be much faster without it.

If you use a pure ID-based selector then jQuery can use the native document.getElementById() call. In practise this is probably the most optimal:

$('#navcontainer').children('a').hide();

Upvotes: 2

Kyle Macey
Kyle Macey

Reputation: 8154

You mixed up the class and Id selector

$('#navcontainer a').hide();
$('#navcontainer > a').hide();

Upvotes: 4

Adrian Bratu
Adrian Bratu

Reputation: 508

$('div#navcontainer a').hide();
$('div#navcontainer > a').hide();

Upvotes: 0

xpapad
xpapad

Reputation: 4456

You need $('div#navcontainer'), your code is looking for navcontainer class rather than id.

Upvotes: 1

Shyju
Shyju

Reputation: 218952

if you have the div with class navcontainer, use

 $(".navcontainer a").hide()

if you have a div with id navcontainer. use

 $("#navcontainer a").hide()

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227310

$('div#navcontainer a').hide();

. is for classes, you want # for IDs.

Since IDs are (should be) unique, you don't need the div prefix.

$('#navcontainer a').hide();

Upvotes: 2

rosscj2533
rosscj2533

Reputation: 9323

Based on your html, you need to use the id selector -

$('div#navcontainer > a').hide();

Upvotes: 0

Related Questions