Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - Select all unlinked items in a nested list with jquery

I have the following HTML

 <ul>
     <li><a ...>item 1</a></li>
     <li>item 2
          <ul>
              <li><a ...>item 2-a</a></li>
              <li><a ...>item 2-b</a></li>
         </ul>
    </li>
    <li><a ...>item 3</a></li>
    <li>item 4
          <ul>
              <li><a ...>item 4-a</a></li>
              <li><a ...>item 4-b</a></li>
         </ul>
    </li>
    <li><a ...>item 5</a></li>
    <li><a ...>item 6</a></li>
 </ul>

I want to add a class to 'item 2' and 'item 4' with jquery using .has but can't find a way.


I want to clarify my question: I have a nested list with an unknown amount of items where some items are not linked. I want to add a class to all unliked items.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to add the class depending to the content of the li you could use :contains selector :

$( "li:contains('item 2')" ).addClass('X');

Or filter and check text() content :

$( "li" ).filter(function(){
    return $(this).text()==='item 4';
}).addClass('X');

If you want to add class using the index's use .eq() like Robiseb's answer show.

EDIT :

I don't know how many <li> without a link will be in the list. And I don't know what the text inside the <li> will be.

You could use :

$("li:not(:has(>a))").addClass('X');

Hope this helps.

$("li:not(:has(>a))").addClass('X');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a ...>item 1</a></li>
  <li>item 2
    <ul>
      <li><a ...>item 2-a</a></li>
      <li><a ...>item 2-b</a></li>
    </ul>
  </li>
  <li><a ...>item 3</a></li>
  <li>item 4
    <ul>
      <li><a ...>item 4-a</a></li>
      <li><a ...>item 4-b</a></li>
    </ul>
  </li>
  <li><a ...>item 5</a></li>
  <li><a ...>item 6</a></li>
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...