Reputation: 325
HTML:
<ul id="column">
<li id="widget8">
<div class="testhub"></div>
</li>
</ul>
JS:
if ($("#widget8").parent("#dock")) {
$(".testhub").html("<p>dock</p>");
}
else {
$(".testhub").html("<p>not dock</p>");
}
CSS:
#dock {
width: 90%;
height: 100px;
background-color: blue;
}
#column {
width: 90%;
height: 100px;
background-color: red;
}
#widget8 {
width: 90%;
height: 50px;
background-color: yellow;
}
.testhub {
width 50%;
height: 25px;
background-color: black;
color: white;
}
All i am trying to do is get the ul that the li is in and if it is on #dock then write something to testhub. But doesn't seem to work, check the jsfiddle.
I presume i am using parent incorrectly.
Upvotes: 0
Views: 163
Reputation: 26320
The first problem is that on your fiddle you use 2 ul
s with the same id
. Use class instead.
You have to loop thrue your li
s and check parent's length.
$(".widget8").each(function) {
var $element = $(this).parent("#dock");
if($element.length > 0) {
var message = 'dock';
}
else {
var message = 'not dock';
}
$($element, this).html('<p>' + message + '</p>');
});
So if you just want to test if has id you just have to use the right selector.
$('#dock .widget8').html('<p>dock</p>');
The selector above get elements which are inside #dock
and has class .widget8
.
Upvotes: 2
Reputation: 34107
Try this: Working demo http://jsfiddle.net/268mh/
Please note you can never have same id's in DOM. SO I have made widget8
to class instead!
Rest hope demo helps the cause! :)
code
$(".widget8").each(function() {
if ($(this).parent().prop("id") == "dock") {
$(this).find(".testhub").html("<p>dock</p>");
}
else {
$(this).find(".testhub").html("<p>not dock</p>");
}
});
HTML
<ul id="dock">
<li class="widget8">
<div class="testhub"></div>
</li>
</ul>
<ul id="column">
<li class="widget8">
<div class="testhub"></div>
</li>
</ul>
Upvotes: 2
Reputation: 183301
The problem is that this expression:
$("#widget8").parent("#dock")
evaluates to a jQuery object, and objects are always "true" values in JavaScript. (Always. Even new Boolean(false)
is a "true" value.)
To see if the above jQuery object contains any actual elements, you can use the .length
property:
if ($("#widget8").parent("#dock").length) {
(But I agree with jeff that it's more clear to write parent().is("#dock")
: get the parent, check if it's #dock
, rather than get the parent-if-it's-#dock
, see if it exists.)
Upvotes: 1
Reputation: 94101
You forgot length
to check if it actually exists.
if ($("#widget8").parent("#dock").length)
---^---
Upvotes: 1
Reputation: 8348
If you're trying to test the parent id
, you can use this:
if ($("#widget8").parent().is("#dock")) {
$(".testhub").html("<p>dock</p>");
}
else {
$(".testhub").html("<p>not dock</p>");
}
Upvotes: 0