如何将所有<a> tags from my </a> <ul> <a> which is my parent node

时间:2018-06-19 08:23:11

标签: jquery html

I want to be able to select all the <a> tags from my a parent tag of <ul>. I tried $("ul").children().children(); but is there a better way

<ul class="chat-inbox" id="chat-inbox">
  <li><input type="text" class="form-control" placeholder="Search..."></li>
  <!-- ko foreach: messageModels() -->
  <li>
    <a data-bind="click:$parent.startChat.bind()" style="cursor: pointer" href="#">
      <div class="media">
        <div class="pull-left">
          <img class="media-object img-circle" src="assets/images/ici-avatar.jpg">
          <span class="badge badge-red" data-bind="text:unreadMessagesCount()">1</span>
        </div>
        <div class="media-body">
          <p class="media-heading"><span data-bind="text:friend.userName()">Ing. Imrich Kamarel</span> <span class="time" data-bind="text: $parent.convertTime(messages()[messages().length - 1].dateCreated())">12:44</span></p>
          <span class="message" data-bind="text:messages()[messages().length - 1].message()">Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.</span>
          <div class="chat-actions">
            <span class="mark-unread" title="Mark as unread"><i class="fa fa-circle-o"></i></span>
            <span class="archive" title="Archive"><i class="fa fa-times"></i></span>
          </div>
        </div>
      </div>
    </a>
  </li>
  <!-- /ko -->
</ul>

2 个答案:

答案 0 :(得分:1)

$('ul#chat-inbox li > a');
//also worked 
$('ul#chat-inbox li  a');

有些li和我已经添加了测试尝试上面的代码。

enter image description here

答案 1 :(得分:1)

这完全取决于您对代码的处理方式,以及您是否将要链接事件。

如果您只想选择<a>中的所有<ul>元素,那么最快捷,最通用的选项是:

$('ul a');

但是,如果您想链接事件,例如:

$(..).addClass('..');

然后你最好按ID使用jQuery .find和target元素。例如,根据您的代码,性能的最佳选择是:

$('#chat-inbox').find('a').addClass('test');