Well it is a specification that in HTML you cannot have more than one element on a page with a given id. But in ordinary HTML and css this rarely if ever causes any problem. In javascript though, if you look for an element with an id and there's more than one, you either get an error or only the first one. jQuery is built on javascript and follows this same model. In both ordinary javascript and jQuery there are ways of looking for elements that will get around this limitation. But in every case it's safer and easier to use class instead of id if multiple elements are involved.
Oh, and if your page looks like this:
HTML Code:
<a href="#" id="book">Book</a> | <a href="#" id="magazine">Magazine</a>
<br />
<div id="wrapper">
<img src="#" class="book" />
</div>
<div id="wrapper">
<img src="#" class="book" />
<img src="#" class="magazine" />
</div>
<div id="wrapper">
<img src="#" class="magazine" />
</div>
before, it will look like that after. You just won't see, when looking at the page in the browser, those elements that have been hidden. They're not actually removed when you use jQuery's .hide() method. They could be if you wanted to do that. It would require another method be used though.
OK, so let's use this HTML:
HTML Code:
<a href="#" id="book">Book</a> | <a href="#" id="magazine">Magazine</a>
<br />
<div class="wrapper">
<img src="#" class="book" />
</div>
<div class="wrapper">
<img src="#" class="book" />
<img src="#" class="magazine" />
</div>
<div class="wrapper">
<img src="#" class="magazine" />
</div>
And, you're probably right about needing if - but only in ordinary javascript. In jQuery you can use its selector syntax and chaining to determine what gets done to which elements (I added text to the divs to make it easier to see what's happening, but if you have real images, you won't need that):
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
$('#book, #magazine').click(function(e){
$('.wrapper').hide().has('.' + this.id).show();
e.preventDefault();
});
});
</script>
</head>
<body>
<a href="#" id="book">Book</a> | <a href="#" id="magazine">Magazine</a>
<br />
<div class="wrapper">
<img src="#" class="book" />
I'm just a book div
</div>
<div class="wrapper">
<img src="#" class="book" />
<img src="#" class="magazine" />
I'm a book and magazine one
</div>
<div class="wrapper">
<img src="#" class="magazine" />
only a magazine here
</div>
</body>
</html>
Bookmarks