检查<li>是否包含<a> with a certain class

时间:2015-12-22 10:21:52

标签: javascript jquery html

I have this and I want to check the first <li> who contains <a> with the class .selected.

I have tried this : $( "li a" ).first().hasClass('selected') but my <li> isn't detected.

Here is my HTML code.

<ul>
  <li>
    <a class="thumbnail selected">
     <img src="thumb1.jpg">
    </a>
  </li>
  <li>
    <a class="thumbnail unselect">
     <img src="thumb2.jpg">
    </a>
  </li>
  <li>
    <a class="thumbnail unselect">
     <img src="thumb3.jpg">
    </a>
  </li>
  <li>
    <a class="thumbnail unselect">
     <img src="thumb4.jpg">
    </a>
  </li>
  <li>
    <a class="thumbnail unselect">
     <img src="thumb5.jpg">
    </a>
  </li>
</ul>

Could you help me ?

2 个答案:

答案 0 :(得分:5)

您可以使用.has()之类的

&#13;
&#13;
$('li:has(a.selected)').first().addClass('found')
&#13;
.found {
  border: 1px solid red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <a class="thumbnail selected">
      <img src="thumb1.jpg">
    </a>
  </li>
  <li>
    <a class="thumbnail unselect">
      <img src="thumb2.jpg">
    </a>
  </li>
  <li>
    <a class="thumbnail unselect">
      <img src="thumb3.jpg">
    </a>
  </li>
  <li>
    <a class="thumbnail unselect">
      <img src="thumb4.jpg">
    </a>
  </li>
  <li>
    <a class="thumbnail unselect">
      <img src="thumb5.jpg">
    </a>
  </li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

对于第一个选定的锚标记,只需尝试此

$('li a.selected:first')