user4563161
user4563161

Reputation:

Jquery If class has matching ID then hide

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.

JSfiddle

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 &amp; should be hidden</li>
  <li id="num-2">iam 3</li>
  <li id="num-3">iam 4</li>
  <li id="num-4">ieam 5 &amp; 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

Answers (4)

billyonecan
billyonecan

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();

Here's a fiddle

Upvotes: 0

Sthe
Sthe

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

nnnnnn
nnnnnn

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

Tushar
Tushar

Reputation: 87233

  1. Use each() to loop over all the li elements inside the #you
  2. 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 &amp; should be hidden</li>
  <li id="num-3">iam 4</li>
  <li id="num-4">ieam 5 &amp; 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>

Demo

Upvotes: 4

Related Questions