Finding text length within a divs children - javascript

So i have an array of divs. each div contains three span elements. Each span element can contain any number of digits.
This is what i have so far:
var arrayOfDivs = $(".avgMaxClass");
$.each(arrayOfDivs, function (index, value) {
});
what i want to do is calculate the total length of all the text within all the spans within the div im iterating through. I can't figure it how to do that.
EDIT:
To be clear i don't want the total text length of all the divs. I want the text length of the current div that im iterating through

$(".avgMaxClass span").text().length;
JSFiddle demo
Edit:
As you stated in your comment that you want to know the length for each DIV, here is another way using jQuery.each():
var avgMaxClass = $('.avgMaxClass');
$.each(avgMaxClass, function(i,item) {
// Output span text length for each item
console.log($("span", item).text().length);
});
JSFiddle demo

Just iterate over the div and find its length.
$(".avgMaxClass").each(function(){
var thisDivsLength = $(this).find('span').text().length;
alert("Current div's length: " + thisDivsLength);
});
$.each is for non-jQuery objects. Use $.fn.each instead.
DEMO

You can use a selector to get the divs and spans at the same time, or to split the logic and show both parts individually, you can use two selectors and loop over the results of each.
var total = 0;
$(".avgMaxClass").each(function(index, value) {
$(value).find("span").each(function(cindex, child) {
total += $(child).text().length;
});
});
$("#result").text("Total length: " + total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avgMaxClass">
<span>1</span>
<span>12</span>
<span>123</span>
</div>
<div class="avgMaxClass">
<span>1234</span>
<pre>12345</pre>
<span>12345</span>
</div>
<div class="avgMaxClass">
<span>123456</span>
<span>1234567</span>
<span>12345678</span>
</div>
<div id="result"></div>

Related

looping over nested array to create elements with js/jquery

I come with a problem, I hope you can help me solve.
I have already searched on this side quite a bit, but couldn't find an answer that solves my problem. I recently worked with looping over objects with jquery each and that worked fine. ATM I need to loop over entries of an array.
This is an example of how the array looks. It contains arrays, which themselves contain the src of an img and the title of the img.
var imgRef = [[http://127.0.0.1:5555/images/imgf0002.png, fig number 1],[http://127.0.0.1:5555/images/imgf0012.png, fig number 12]]
What I would like to do is to loop over the arrays and create a div for each entry. Inside the divs there should be an img containing the src of the other array and a p tag with the name. Then this will be appended to another element on the website.
<div>
<img src="http://127.0.0.1:5555/images/imgf0002.png">
<p>Fig number 1</p>
</div>
<div>
<img src="http://127.0.0.1:5555/images/imgf0012.png">
<p>Fig number 2</p>
</div>
I have started with this. Just to see whether I can loop over the entries, but it didn't work.
$.each(imgRef, function (index, value) {
$('<div />', {
'text': value
}).appendTo('#localImg');
});
var imgRef = [['http://127.0.0.1:5555/images/imgf0002.png', 'fig number 1'],['http://127.0.0.1:5555/images/imgf0012.png', 'fig number 12']]
$.each(imgRef, function(index, value){
$('.localImg').append('<div><img src="'+value[0]+'"><p>'+value[1]+'</p></div>');
});
you've got to iterate over the array with arr.forEach((elem) => {}) or other iterator methods. Since each of elements of the main array, is an array of two elements, you can use array destructuring and use [url, title] instead of elem in the iterator function. Then in the body create the html string from title and url and append it into your target using $.append method.
let theArray = [["url1","title1"],["url2","title2"] /*,...*/];
theArray.forEach(([url, title]) => {
$('#localImg').append(`<div>
<img src="${url}">
<p>${title}</p>
</div>`);
});
var imgRef = [['http://127.0.0.1:5555/images/imgf0002.png', 'fig number 1'],['http://127.0.0.1:5555/images/imgf0012.png', 'fig number 12']]
$.each(imgRef, function (index, [src, text]) {
// create the div element
const div = $("<div></div>")
// create the image and add src for it.
const img = $('<img />', {
src,
});
// create the p element and add the text to it.
const p = $('<p></p>', {
text
})
// append both image and p in the div
div.append([img, p])
// then insert the block inside the localImage container.
$('#localImg').append(div)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="localImg"></div>

How to get index, position number of element with certain class with jQuery

I have this markup
<div class="parent">
<div class="one"></div>
<div class="two"></div>
<div class="one"></div>
<div class="two"></div>
</div>
My question is: how to get "index" number of element with class two. I'm not asking of regular index number of element in parent div. I need to know that when i'm clicking at first element with class one that next two element have 0 index or it's first element in this list with class two, and so on.
I've tried with index() method and eq() and always i have the real index number of this element in parent div. I hope this is clear, thx for help.
You need to find the elements index in collection of element with sameclass:
$('.parent > div').click(function(){
var index;
if($(this).is('.one'))
index = $('.parent > .one').index(this);
else
index = $('.parent > .two').index(this);
});
This should be the faster way to get the index you are looking for.
Instead of retrieving all matches, it just counts the number of elements of the same class among previous leafs in your DOM.
Also, it allows having multiple <div class="parent"> and still work
$('.parent div').click(function() {
// Retrieve clicked element class (one, two)
var elClass = $(this).attr('class');
// Retrieve all previous elements that have the same class
// and count them
var prevElmts = $(this).prevAll('.' + elClass),
numPrevElements = prevElmts.length;
console.log(numPrevElements);
})
Using jquery you can find index of element which have same class name or tag name
$(".class_name").on("event_name", function() {
var index=($(this).index());
console.log('index : ',index);
});
This may work for you.
var p = $('.parent'),
current = p.filter('.two'),
index = p.index(current);

jQuery/JavaScript - Counting child elements in multiple parent elements

I'm creating a directory of apps, each of which has it's own comments which are hidden until the user opens them. I'd like to show the number of comments that each app currently contains but I can only get it display the total number of comments on the page (See JSFiddle: http://jsfiddle.net/9M4nw/2/ for a basic example). Ideally it should display 2 in the top box and 4 in the bottom box. I thought I might need to use an array or something along those lines?
Here is my code:
HTML
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
jQuery
$(".parent").each(function(index){
var numChilds = $(".child").length;
$(".parent").append(numChilds);
});
You have to select the current HTML element (with class parent). Then, you will use it in selecting the length of elements with class .child and the html for .counter.
Using $(this) you can select the current HTML element from each() function.
Corrected code:
$(".parent").each(function(){
var numChilds = $(".child", $(this)).length;
$(".counter", $(this)).html(numChilds);
});
JSFIDDLE
The problem is you need to limit the scope of the element look up to the desired parent element
$(".parent").each(function(index){
var numChilds = $(".child", this).length;
$(".counter", this).html(numChilds);
});
Another version
$(".parent").each(function(index){
var $this = $(this);
var numChilds = $this.find(".child").length;
$this.find(".counter").html(numChilds);
});
Demo: Fiddle
This would require some extra work to show the number of childs in a more elegan way, but it should be enough to understand the idea
$(".parent").each(function(index){
var $this = $(this);
var numChilds = $this.find(".child").length;
$this.append("<span>" + numChilds + "</span>");
});
This code will help you to get number of children separately for each parent div :-
$(document).ready(function () {
$(".parent").each(function (i) {
$(this).children().length;
});
});
Try this hope this may help you.Vote

How to find number of <ul> inside each div

I have a large file of this form [similar div's throughout]. I want to be able to select a div, find the number of ul's in it and traverse through each of them to get value of each li in it.
<div class="experiment">
<div class="experiment-number">5</div>
<ul class="data-values">
<li><div></div> 14</li>
<li><div></div> 15</li>
</ul>
<ul class="data-values">
<li><div></div> 16</li>
</ul>
</div>
I have tried looping through all experiment divs, then select the uls, but it selects all the ul in the page, not only the ones under current div.
$('experiment ul').eq('$i');
Your HTML is currently incorrect, since you're simply starting new <div> and <ul> elements rather than closing the existing ones. Ignoring that because it's trivial to fix, we'll move on to the real issue.
You need to select all of the <div class="experiment"> elements, then iterate through them. To do that you can use the .each() function. It might look something like this:
var experiments = $('.experiment'); // all of them
experiments.each(function(i, val) { // will iterate over that list, one at a time
var experiment = $(this); // this will be the specific div for this iteration
console.log("Experiment: " + experiment.find('.experiment-number').text());
// outputs the experiment number
console.log("Experiment ULs: " + experiment.find('ul').length);
// number of <ul> elements in this <div>
var total = 0;
experiment.find('ul.data-values li').each(function() {
total += parseInt($(this).text(), 10);
});
console.log("Experiment total: " + total);
// outputs the total of the <li> elements text values
});
Take a look at this jsFiddle demo.
to get all the ul inside div.experiment
var ul = $('.experiment').find('ul');
and to get all li elements inside each ul found above
ul.each(function(list) {
var li = $(list).find('li');
});
$('.experiment').each(function() {
var cnt = $(this).children('ul').length;
$(this).find('.experiment-number').text(cnt);
});
First of all you need to work out the correct selector for each DIV.
The selector you want is:
".experiment"
Notice the . to denote a class selector.
This will allow you access to each DIV element. If you then want to loop though each of these, you can do so like this:
$(".experiment").each(function(){
var div = $(this);
var elementsInThisDiv = div.find("ul");
//you now have a list of all UL elements in the current DIV only
var numberOfElements = elementsInThisDiv.length;
//you now have a count of UL elements belonging to this DIV only
//you can loop the UL elements here
$(elementsInThisDiv).each(function(){
var ul = $(this);
//do something with the UL element
//like get the LI elements...
var liElements = ul.find("li");
});
});
IMPORTANT: There is also an error with your HTML, you need to close your <ul> elements correctly using </ul>

arithmetics on selected DOM element text

I've got a simple jQuery $("span.value") which select nodes containing text. This text is guaranteed to be an integer. How do I calculate the sum of all selected node's text, and place the sum into another node?
<span class="value">3</span>
<span class="value">4</span>
<span class="value">5</span>
<span class="sum">?</span>
You could do this:
var sum = 0;
$('.value').each(function(index, el) {
sum += parseInt($(this).text());
});
$('.sum').text(sum); //careful - will set the text for *all* elements with class = sum
I'd suggest using an id instead of a class for the sum <span>, even if you're sure there's going to be just one. IMO, it's be less error-prone..

Categories

Resources