Reputation:
What I'm trying to do here is check if an element has the same id
as a class
in another element if so hide the matching id
.
So far this is what I have came up with but it doesn't seem to kick.
var theid = $('#me li').attr('id');
if ($('#you li').hasClass( theid )) {
$('#me li#'+theid+'').hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<ul id="me">
<li id="num-0">iam 1</li>
<li id="num-1">ieam 2 & should be hidden</li>
<li id="num-2">iam 3</li>
<li id="num-3">iam 4</li>
<li id="num-4">ieam 5 & should be hidden</li>
<li id="num-5">iam 6</li>
</ul>
<ul id="you">
<li class="num-1">iam killer</li>
<li class="num-4">iam killer</li>
</ul>
Upvotes: 1
Views: 1448
Reputation: 20270
You could filter
the #me li
's, returning elements where their id
exists as a class in #you li
's, then just hide them. This would also work for multiple classes:
$('#me li').filter(function() {
return $('#you').has('.' + this.id).length;
}).hide();
Upvotes: 0
Reputation: 2705
Try this for your jquery:
$(function() {
$("#you li").each(function(){
var theid = $(this).attr('class');
$('#'+theid).hide();
});
});
Demo: https://jsfiddle.net/nkem9o7o/
Upvotes: 0
Reputation: 150070
When you use the .attr()
method on a jQuery object that contains multiple elements, it just returns the attribute from the first element. You need to loop over each element and check them one at a time.
It is, however, OK for your purposes to use .hasClass()
on the set of all of the #you
elements, because .hasClass()
will return true
if any of the elements in the set has that class. So:
var you = $('#you li');
$('#me li').each(function() {
if (you.hasClass(this.id))
$(this).hide();
});
Note that I'm keeping a reference to the $('#you li')
jQuery object in the variable you
to save selecting those elements again every time in the loop.
Demo: https://jsfiddle.net/d65sz4js/2/
Upvotes: 0
Reputation: 87233
each()
to loop over all the li
elements inside the #you
hide()
the elements having the id
same as the class
of current element in loop.$('#you li').each(function() {
$('#' + $(this).attr('class')).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<ul id="me">
<li id="num-0">iam 1</li>
<li id="num-1">ieam 2</li>
<li id="num-2">iam 3 & should be hidden</li>
<li id="num-3">iam 4</li>
<li id="num-4">ieam 5 & should be hidden</li>
<li id="num-5">iam 6</li>
</ul>
<ul id="you">
<li class="num-2">iam killer</li>
<li class="num-4">iam killer</li>
</ul>
Upvotes: 4