简体   繁体   中英

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:

<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):

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.

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. In the example below I used click , but any event will work.

 $('.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. map() does this implicitly:

 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. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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