简体   繁体   English

如何获取每个匹配元素的特定子元素的数量

[英]How to get the number of particular child elements for each matched element

How to get the number of matched child elements for each matched parent element?如何获取每个匹配的父元素的匹配子元素的数量? HTML: HTML:

<div class="parent">
   Today I've eaten <mark>potatoes</mark>
</div>
<div class="parent"> 
   Yesterday I <mark>jumped</mark> and <mark>educated</mark> myself.
</div>

JS (jQuery): JS(jQuery):

var context = $(".parent");
var amountOfMarksInside = context.each().has("mark").children("mark").length;

The idea is to get the number of marks inside a particular parent while looping through all parents of a "parent" class.这个想法是在循环遍历“父”类的所有父时,获取特定父内的标记数。 How can I do it?我该怎么做? Both JS and jQuery solutions are appreciated. JS 和 jQuery 解决方案都受到赞赏。

To get the specific parent you need to attach an event handler to it in order to have a reference you can use to select the child mark elements.要获得特定的父级,您需要将一个事件处理程序附加到它,以便获得可用于选择子mark元素的参考。 In the example below I used click , but any event will work.在下面的示例中,我使用了click ,但任何事件都可以工作。

 $('.parent').on('click', e => { let numMarks = $(e.currentTarget).children('mark').length; console.log(numMarks); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parent"> Today I've eaten <mark>potatoes</mark> </div> <div class="parent"> Yesterday I <mark>jumped</mark> and <mark>educated</mark> myself. </div>

Alternatively, if you want to get the count for all .parent elements you could use a loop.或者,如果您想获取所有.parent元素的计数,您可以使用循环。 map() does this implicitly: map()隐式执行此操作:

 let numMarks = $('.parent').map((i, el) => $(el).children('mark').length).get(); console.log(numMarks);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parent"> Today I've eaten <mark>potatoes</mark> </div> <div class="parent"> Yesterday I <mark>jumped</mark> and <mark>educated</mark> myself. </div>

You can achieve this using vanilla JS, no need of Jquery.您可以使用 vanilla JS 实现这一点,不需要 Jquery。 Just get all the mark tags inside parent class like this.只需像这样获取父类中的所有标记标签。

 console.log(document.querySelectorAll('.parent mark').length)
 <div class="parent"> Today I've eaten <mark>potatoes</mark> </div> <div class="parent"> Yesterday I <mark>jumped</mark> and <mark>educated</mark> myself. </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM