Reputation: 540
I am trying to access an id that is nested, but is also duplicated in a number of areas. Something similar to the following sample markup:
<td id='one'>
<p id='up'>up 1</p>
<p id='down'>down 1</p>
</td>
<td id='two'>
<p id='up'>up 2</p>
<p id='down'>down 2</p>
</td>
I tried using
$('#three').click(function(){
$('td#one p#up').hide();
});
but that doesn't work. But this does work:
$('#four').click(function(){
$('p#up').hide();
});
Can someone explain how to hide specifically the p tag with the text 'up 1'?
Fiddle: http://jsfiddle.net/6UBwD/
All help is appreciated
EDIT: Changed id's to classes, and still no dice. What am I doing wrong? FIDDLE: http://jsfiddle.net/6UBwD/4/
Upvotes: 0
Views: 812
Reputation: 241
First of all, this is not valid html, according to the HTML 5 specification which says ID must be unique within a document.
To answer your question, you can create "nested" JQuery selectors by separating them with a simple space ie jQuery('#mySelectorId1 #mySelectorId2')
.
Upvotes: 1
Reputation: 3888
The short answer is that you shouldn't have <td>
elements inside <ul>
. See this for more information.
I replaced td
with div
<ul>
<div id='one'>
<p id='up'>up 1</p>
<p id='down'>down 1</p>
</div>
<div id='two'>
<p id='up'>up 2</p>
<p id='down'>down 2</p>
</div>
<div>
<button id='three'>click here - doesnt work</button>
</div>
<div>
<button id='four'>click here -- works</button>
</div>
</ul>
However, as other's have pointed out, this works but isn't reliable. You cannot have multiple elements with the same id
in the same document. You should use class
instead of id
. You can then do
$('#three').click(function(){
$('#one p.up').hide();
});
$('#four').click(function(){
$('p.up').hide();
});
HTML:
<ul>
<div id='one'>
<p class='up'>up 1</p> <!-- Notice class="up" instead of id="up" -->
<!-- Alternatively, you could do "up1", "up2", so on as ids -->
<p class='down'>down 1</p>
</div>
<div id='two'>
<p class='up'>up 2</p>
<p class='down'>down 2</p>
</div>
<div>
<button id='three'>click here - doesnt work</button>
</div>
<div>
<button id='four'>click here -- works</button>
</div>
</ul>
Upvotes: 4
Reputation: 9468
As noted in the comments you shouldn't have duplicate ids.
One option is to give each <p>
a unique id and hide the specific one that you want to hide
$('#three').click(function(){
$('#up1').hide();
});
Upvotes: 0
Reputation: 7488
ID should be an unique within the HTML document. Use class instead. See this: http://www.w3schools.com/tags/att_global_id.asp
Upvotes: 1