jQuery/JavaScript - Counting child elements in multiple parent elements - javascript

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

Related

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

Increment div class by +1 on click

I'm sure this is an easy question but I cannot figure it out.
I basically have a div with a number, 'div-1' for example, and need to +1 to the number every time another div is clicked. e.g. 'div-2' 'div-3' etc..
When you say a div with a number, It should be on id attribute.
<div class="your_div_selector" id="div-1">
so, in your javascript, using jquery and when the other div is clicked, just do this:
var div_id = $('.your_div_selector').attr("id")
var new_id = 1 + parseInt(div_id.split("-").pop());
Based on what you've described, it looks like you have an HTML div, which starts with a class of div-1. Every time the div is clicked, you want the div-n class to be replaced with a div-(n+1) class.
This is easily accomplished with an onclick listener.
<div id="mydiv" class="div-1"></div>
<script>
var mydiv = document.getElementById('mydiv');
mydiv.currentClass = 1;
mydiv.addEventListener('click', function() {
mydiv.classList.remove('div-' + mydiv.currentClass);
mydiv.classList.add('div-' + (++mydiv.currentClass));
});
</script>
Note that there should be a better solution, depending on your specific problem.
<div class="yourDivClass" id="myDiv"></div> <button id="incriment" onclick="incrementDivClass()">Click</button>
function incrementDivClass()
{
var divIncriment = ($('.yourDivClass').length);
$('#myDiv').append('<div class="yourDivClass" id="div-'+divIncriment+'">div-'+divIncriment+'</div>')
}
Demo

Jquery to check height and add class

I am trying to check which div has bigger height and than place a class inside the one that is greater.
I have this code
$(document).ready(function () {
var sideNavMenu = $(".col-md-3").height();
var mainColumn = $(".col-md-9").height();
if (sideNavMenu > mainColumn)
{
$(".col-md-3").addClass('dotRight');
}
else
{
$(".col-md-9").addClass('dotLeft');
}
});
The goal here is to check if sideNavMenu is greater than mainColumn than place dotRight on its div tag.
If the mainColumn is greater, then place dotLeft on its div tag.
But its not working.
Any suggestion how to change/improve it.
Thanks a lot
You should reference these by IDs and not classes, since there can be multiple elements with these class names on the page. There should only be one with each ID.
$(document).ready(function () {
var sideNavMenu = $("#sidebar").height();
var mainColumn = $("#main").height();
if (sideNavMenu > mainColumn) {
$("#sidebar").addClass('dotRight');
} else {
$(".#main").addClass('dotLeft');
}
});
Of course, you need to add the id's to your <div>s respectively.
The jQuery docs say:
Get the current computed height for the first element in the set of matched elements or set the height of every matched element.
But, I was just playing with it in jsfiddle and it seems to return an object containing the height of the first element.
http://jsfiddle.net/wwx2m/2/
Which means you should be able to do:
$(document).ready(function () {
var sideNavMenu = $(".col-md-3").height();
var mainColumn = $(".col-md-9").height();
if (JSON.stringify(sideNavMenu) > JSON.stringify(mainColumn)) {
$(".col-md-3").addClass('dotRight');
} else {
$(".col-md-9").addClass('dotLeft');
}
});
But the first way I said is preferred. This is not stable, since there can be more objects introduced with the same class. The only reason I'm even mentioning it is to explain why you were having problems with your original code. :)
http://jsfiddle.net/wwx2m/4/
I put the jsfiddle together for you
<html>
<div class='col-md-3'>
</div>
<div class='col-md-9'>
</div>
<script>
var sideNavMenu = $(".col-md-3").height();
var mainColumn = $(".col-md-9").height();
if (sideNavMenu > mainColumn){
$(".col-md-3").addClass('dotRight');
}
else{
$(".col-md-9").addClass('dotLeft');
}
jsFiddle
updated jsFiddle with Animation

jQuery select href values in nested divds

Although I found several answers to select a href attribute neither of them is working for me. Maybe someone can help.
The html is as follows
<div class="galleryitem">
<div class="itemlink">
Page
</div>
<div class="itemimg">
test1.png
</div>
</div>
<div class="galleryitem">
<div class="itemlink">
Page 1
</div>
<div class="itemimg">
test2.png
</div>
</div>
Now i want to geht all the attribute values in the hrefs and tried with
$('.galleryitem').each(function() {
var link = $(this).children('itemlink a').attr('href');
var img = $(this).children(".itemimg a").attr("href");
//jQuery("#somediv").append("<a href='" + link + "'><img class='cloudcarousel' src='" + img + "'/></a>");
});
I dont know why link and img are undefined. Even $(this).children('.itemlink a') is undefined.
Can anyone help on this?
Try with find
$('.galleryitem').each(function() {
var link = $(this).find('itemlink a').attr('href');
var img = $(this).find(".itemimg a").attr("href");
//...
})
you want to sure the .find() method instead of .children which only grabs the immediate descendants. (you also have a small error missing the period in itemlink)
var link = $(this).find('.itemlink a').attr('href');
var img = $(this).find(".itemimg a").attr("href");
should work for you, and here is a fiddle: http://jsfiddle.net/hQeu3/
the reason .children doesn't works is that there are no immediate descendents that match this selector '.itemlink a'. jQuery grabs the divs (".itemlink"), and then tries to filter to the selector, which fails in this case. it is essentially equal to
$(this).children().filter('.itemlink a'); //won't work!
if you want to use children you could do
$(this).children('.itemlink').children("a").attr('href');
You could do as follows:
$('.galleryitem').each(function() {
var link = $('.itemlink > a', this).attr('href');
var img = $('.itemimg > a', this).attr('href');
});
which take into account that .itemlink and .itemimg are a direct parent of the <a> element.

How to get the first inner element?

So I want to get the first <a> tag in this <div>. This is really driving me nuts. Thanks for any help.
HTML
<div id="PGD" class="album" onmouseover="load(this)">
<a class="dl" href="#">DOWNLOAD</a>
</div>
Javascript
function load(dl)
{
var ID = $(dl).attr('id');
var elemnt = $('ID:first').attr('id');
}
Non-jQuery: (was not tagged with jQuery before, so I included this)
If you want to get the first child element only:
var element = document.getElementById('PGD').children[0];
If you want to get the first anchor element:
var element = document.getElementById('PGD').getElementsByTagName('a')[0];
With jQuery:
var element = $('#PGD').find('a:first');
// or, to avoid jQuery's pseudo selecors:
// var element = $('#PGD').find('a').first();
and actually your function can just be
function load(dl)
{
var element = $(dl).find('a:first');
}
Update:
As you are using jQuery, I suggest to not attach the click handler in your HTML markup. Do it the jQuery way:
$(function() {
$("#PGD").mouseover(function() {
$(this).find('a:first').attr('display','inline');
alert($(this).find('a:first').attr('display'));
});
});
and your HTML:
<div id="PGD" class="album">
<a class="dl" href="#">DOWNLOAD</a>
</div>
​See for yourself: http://jsfiddle.net/GWgjB/
$("#PGD").children("a:first")
This will give you the first child "a" tag, but not the descendents. E.g.
<div id="log">
<p>Foo</p>
Hello
Hello
</div>
Will give you : Hello
$(ID).find(':first')
See find jQuery command.
$('#PGD').find('a:first')
Actualy I've not understanding problem, so I'm trying correct your function, to make it clear for you:
function load(dl)
{
// var ID = $(dl).attr('id');
// var elemnt = $('ID:first').attr('id'); // Here is error-mast be like $(ID+':first')
var ID = $(dl).attr('id');
var elemnt = $(ID).find('*:first').attr('id');
}
I supose dl that is $('#PGD'). But child element A have not attribute id, what are you trying to find?
Also See: http://api.jquery.com/category/selectors/

Categories

Resources