Reputation: 671
I am trying to remove an element in jquery if the contents are equal to a variable set in jquery. In this example I am trying to remove .sub3 as the contents are equal to the variable set.
<div class="sub1">
<a href="/large.jpg" class="group1 cboxElement">
<img border="0" alt="" src="/thumb.jpg">
</a>
</div>
<div class="sub2">
<a href="/029-large.jpg" class="group1 cboxElement">
<img border="0" alt="" src="/029-thumb.jpg">
</a>
</div>
<div class="sub3">
<a href="" class="group1 cboxElement"></a>
</div>
The Jquery I have come up with just removes the whole element regardless
var nopic = <a class="group1 cboxElement" href=""></a>;
if($.trim($(".sub1").text()) == nopic) {
$(".sub1").remove();
}
if($.trim($(".sub2").text()) == nopic) {
$(".sub2").remove();
}
if($.trim($(".sub3").text()) == nopic) {
$(".sub3").remove();
}
Thanks for any pointers!
Upvotes: 1
Views: 1911
Reputation: 7032
One line, simple case that works on all empty links:
$('div[class^="sub"] a.group1.cboxElement[href=""]').parent('div').remove()
Upvotes: 2
Reputation: 7863
I think you may be going about this backwards. What you are trying to do is remove a div
if it contains that link tag. It would probably be easier to find the a
you're looking for and remove it's parent.
$('a.group1.cboxElement').parents('div[class^="sub"]').remove();
Upvotes: 0
Reputation: 41767
If your intent is to just remove the inner div that does not contain an image the following will suffice:
$('div[class^="sub"]').filter(':not(:has(img))').remove();
Upvotes: 2
Reputation: 17573
You've got three problems I can see:
nopic
variable. You need quotes around the value you're assigning to it..subX
elements don't have any text inside them. They have html. So you should be using the .html()
method rather than .text()
.<a>
tag in .sub3
(which I assume is what you're using to test). That's because the href
and class
attributes are reversed.Here's the working JS, as well as a live example:
var nopic = '<a href="" class="group1 cboxElement"></a>';
if($.trim($(".sub1").html()) == nopic) {
$(".sub1").remove();
}
if($.trim($(".sub2").html()) == nopic) {
$(".sub2").remove();
}
if($.trim($(".sub3").html()) == nopic) {
$(".sub3").remove();
}
Upvotes: 0
Reputation: 360882
.text()
returns the text content of a node, not its HTML. You want .html()
instead.
e.g.
Hello$('#blah').text() -> Hello
$('#blah').html() -> <a href="somewhere">Hello</a>
Upvotes: 0
Reputation: 76910
You should use html()
var nopic = '<a class="group1 cboxElement" href=""></a>';
if($.trim($(".sub3").html()) == nopic) {
$(".sub3").remove();
}
Upvotes: 0