user1400915 user1400915 - 6 months ago 13
Javascript Question

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

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>

Comments