Skip to content
Advertisement

Closest function in jQuery and extracting the elements

I have a html fragment as follows:

<div id="samplediv">
  <ul>
   <li name="A">
     <a id="A">
   </li>

   <li name="B">
     <a id="B">
   </li>
   </ul>
</div>

I have a text called:

var text = "B";

I have want to check if the text matches with any of the elements of li and add a class name “disable” for the anchor element not matching with text. I my case I want to add a class called “disable” for

<a id="A">

This is what I have tried:

$("#samplediv li").each(function() {

 if($(this).name != text){
   $(this).closest("a").addClass("disabled");
}
});

But the thing here is $(this).name is evaluating to "undefined" . What is it that I am missing?

Edit: Due to typo ,had missed the tag

Advertisement

Answer

There are multiple issues,

  • $(this) returns a jQuery object which does not have name property, instead you can use $(this).attr('name')
  • .closest() is used to find the ancestor element, but the a is a descendant of the li element, so you need to use find()

You can find all the li elements which does not have the given name and then find the a element within it like

var text = 'B';
$("#samplediv li").not('[name="' + text + '"]').find("a").addClass("disabled");
a.disabled {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="samplediv">
  <ul>
    <li name="A">
      <a id="A">a</a>
    </li>

    <li name="B">
      <a id="B">b</a>
    </li>
  </ul>
</div>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement