Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested ID in JQuery selector

I am trying to change the href of an a nested in a div called blink3:

$('#blink3 #backLink').attr('href',"#item5");

Where the html code is as follows:

<div style="float:left;text-align:center;" id="blink3">
<a href="#item4" class="panel" id="backLink">
<div class="divBack"></div></a>
</div>

works well in all browsers - NOT IE 7 and I cannot figure out why, doesn't change the href.

Is this a IE 7 bug? JQuery? anything wrong with my code?

Any solutions?

like image 384
NinaNa Avatar asked Jul 12 '11 13:07

NinaNa


3 Answers

Nick Craver (omg, where have you been around?) already stated it in a comment. It totally makes no sense to create a selector like #id #id because an ID has to be unique within your DOM by definition.

It looks like you break that rule and therefore, jQuery might select a wrong node.

You should replace your "backlink" id's with classes and go for the selector like

$('#blink3 .backLink');
like image 173
jAndy Avatar answered Nov 18 '22 09:11

jAndy


I don't see any duplication of ID's in the question and I too had the same question even though all of my ID's are unique. A perfectly valid reason for wanting to do nested ID selectors is to retrieve an element if and only if it is a child of a specific parent. I've run into this with drag and drop UIs as well as tree nodes. While not a selector, this is what I've used in the past:

$("#parentId").find("#childId")
like image 6
LouD Avatar answered Nov 18 '22 08:11

LouD


IDs are supposed to be unique within a page. As Nick implies, you should have only one ID with the value of backlink. So a selector of $('#backlink') should be enough by itself. If you have more than one ID with the value backlink, then your HTML is wrong and you should fix that instead.

like image 3
Craig Stuntz Avatar answered Nov 18 '22 09:11

Craig Stuntz