Using the jQuery each function to count divs with the same class - javascript

I created a css class for 8 divs, I need to use the each function of jquery to count the divs and show the result in the page's html, example: "8 divs appear".
I created a code but it doesn't work, it doesn't show the result.
code:
<script>
$( ".class" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
</script>

if you just want to count them, you can do:
$('.class').length

From each() method to get whole same class divs index + content or You want to count how many divs has same class then simply use .length.
Note: Check on Full page. then you can see same class divs count result.
// Console inded with each div text.
$('.sameclass').each(function(index){
console.log(index +':'+ $(this).text());
});
//Count How many divs has (sameclass) class.
$('.result').text($('.sameclass').length);
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<div class="sameclass">Text #1</div>
<div class="sameclass">Text #2</div>
<div class="sameclass">Text #3</div>
<div class="sameclass">Text #4</div>
<div class="sameclass">Text #5</div>
<div class="sameclass">Text #6</div>
<div class="sameclass">Text #7</div>
<div class="sameclass">Text #8</div>
<hr>
<p>Total divs has (sameclass): <strong class="result"></strong></p>

After a few attempts, I managed to solve the problem.
I created three codes and they worked and gave me the result I wanted. Thanks a lot for the help.
1.
var totalPageProducts;
jQuery('.products-grid .item').each(function(index, value) {
totalPageProducts = index + 1;
jQuery('.show-no').html('Showing '+ totalPageProducts +' products');
});
2.
jQuery(document).ready(function($) {
jQuery('.show-no').html('Showing '+ jQuery('.products-grid .item').length +' products');
});
3.
jQuery('.show-no').html('Showing '+ jQuery('.products-grid .item').length +' products');

Related

How to get the text of the inside element of the next div using jquery?

I have two divs... Then when I clicked the 1st div, i want to get the text inside of h3 of the 2nd div
Here is my codes... But none of the jquery code is working.. any help to fix my code, please... thanks
HTML
<div class="timeline-badge" style="background-image:url(images/couple-9.jpg);">CLICK ME</div>
<div class="timeline-panel">
qqqq
<div class="timeline-heading">
wwww
<h3 class="timeline-title">Hello</h3>
<span class="date"><i class="icon-calendar"></i>February 00, 2017</span>
</div>
<div class="timeline-body">
<p>III</p>
</div>
</div>
JQUERY / JAVASCRIPT
$('.timeline-badge').on('click', function() {
alert($(this).closest(".timeline-panel + div + h3").text());
alert($( '.timeline-badge > div:eq(0) + h3:eq(0)' ).children().text());
alert($(this).nextAll( '.timeline-heading').eq(0).innerhtml);
});
http://jsfiddle.net/rK4qc/119/
The .timeline-panel is next sibling of .timeline-badge. So you should use .next() to selecting it. Then use .find() to finding .timeline-title in it.
$('.timeline-badge').on('click', function() {
var text = $(this).next().find(".timeline-title").text();
console.log(text);
});
$('.timeline-badge').on('click', function() {
var text = $(this).next().find(".timeline-title").text();
console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timeline-badge" style="background-image:url(images/couple-9.jpg);">CLICK ME</div>
<div class="timeline-panel">
qqqq
<div class="timeline-heading">
wwww
<h3 class="timeline-title">Hello</h3>
<span class="date"><i class="icon-calendar"></i>February 00, 2017</span>
</div>
<div class="timeline-body">
<p>III</p>
</div>
</div>
Use Jquery's siblings selectors https://api.jquery.com/siblings/
$('.timeline-badge').on('click', function() {
console.log($(this).siblings());
});
Go get it by the class name of h3
$('.timeline-badge').on('click', function() {
alert($(this).next().find('h3.timeline-title').text());
});
You can get the value of your h3 tag with:
$('div.timeline-panel div.timeline-heading h3.timeline-title').val();
use this code.
$(document).on("click",".timeline-badge",function() {
alert("H3 IS " + $('h3.timeline-title').text());
});
and check this fiddle for the code.
http://jsfiddle.net/rK4qc/121/
For the second div just add div for it and get the text user the .text() function.
this will work for you:-
$('.timeline-badge').on('click', function() {
alert($(this).next().find('h3.timeline-title').text());
});

Targeting Multiple Elements with One Function

I have a function that assigns dynamic classes to my div's. This function is a that runs on the page. After the page loads, all 10 of my primary 's have classes ".info1" or ".info2" etc...
I am trying to write a Jquery function that changes the class of the div you click on, and only that one. Here is what I have attempted:
$(".info" + (i ++)).click(function(){
$(".redditPost").toggleClass("show")
});
I have also tried:
$(".info" + (1 + 1)).click(function(){
$(".redditPost").toggleClass("show")
});
And
$(".info" + (i + 1)).click(function(){
$(".redditPost").toggleClass("show")
});
EDITED MY HTML: DIV RedditPost is actually a sibling to Info's parent
<div class="listrow news">
<div class="newscontainer read">
<div class=".info1"></div>
<div class="redditThumbnail"></div>
<div class="articleheader read">
</div>
<div class="redditPost mediumtext"></div>
</div>
My issue is two fold.
The variable selection for ".info" 1 - 10 isn't working because i doesn't have a value.
If I did target the correct element it would change all ".redditPost" classes instead of just targeting the nearest div.
Try like this.
$("[class^='info']").click(funtion(){
$(this).parent().find('.redditPost').toggleClass("show");
});
Alternative:
$('.listrow').each(function(){
var trigger = $(this).find("[class^='info']");
var target = $(this).find('.redditPost');
trigger.click(function(){
target.toggleClass("show");
});
});
Try this
$("div[class*='info']").click(function(){
$(this).parent().find(".redditPost").toggleClass("show")
});
Explanation:
$("div[class*='info'])
Handles click for every div with a class containing the string 'info'
$(this).parent().find(".redditPost")
Gets the redditPost class of the current clicked div
Since the class attribute can have several classes separated by spaces, you want to use the .filter() method with a RegEx to narrow down the element selection as follows:
$('div[class*="info"]').filter(function() {
return /\binfo\d+\b/g.test( $(this).attr('class') );
}).on('click', function() {
$(this).siblings('.redditPost').toggleClass('show');
});
.show {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="listrow news">
<div class="newscontainer read">
<div class="info1">1</div>
<div class="redditThumbnailinfo">2</div>
<div class="articleheader read">3</div>
<div class="redditPost mediumtext">4</div>
</div>
</div>

How can I dynamically generate a jQuery selector?

I have a page with multiple divs generated dynamically via PHP/MySQL. The div class names are also generated dynamically.
<div class="1er45">Test 1</div>
<div class="25dd58">Test 2</div>
<div class="87f77">Test 3</div>
<div class="87fffas">Test 4</div>
<div class="1er45">Test 1</div>
<div class="25dd58">Test 2</div>
<div class="87fffas">Test 4</div>
<div class="8asdf">Test 5</div>
<div class="25dd58">Test 2</div>
<div class="87fffas">Test 4</div>
<div>...</div>
How can I modify this jQuery selector to match all of the dynamically generated div class names above? I only want to show the first div if there are multiple divs with the same class name.
<script>
$('.classname').not(':first').hide();
</script>
From what I understand probably you need to iterate over all div's and hide all same class names occurrences grater than 1 :
$( 'div[class]' ).each( function() {
$( 'div.' + $( this ).attr( 'class' ).replace( /\s/g, '.' ) + ':gt(0)' ).hide();
});
jsFiddle
I don't really see the point of having a class being dynamically generated.
If you know the pattern of these "ids", you can catch them with a regex.
Assuming that you are only ever going to have one class value in each of those <div>'s, you could acheive what you are asking for in the following code:
var $firstDiv = $("div:first");
var sFirstClass = $firstDiv.attr("class");
if ($("." + sFirstClass).length < 2) {
$firstDiv.hide();
}
That code would:
Retrieve the first div
Get it's class attribute value
Checks to see if there is more than one element with that class value
Hides the first element, if there is not
Iterate through each div, counting occurrences of each class name. Then for each collected class name, hide repeats.
var classNames = {};
$('div').each(function(){
var c = $(this).attr('class');
classNames[c] ? classNames[c]++ : classNames[c] = 1;
});
for (var c in classNames) {
if (classNames[c] > 1)
$('div.' + c).not(':first').hide();
}
http://jsfiddle.net/ne770a5g/

Jquery function is needed

Following code add div on click button. But I want to add classes to all divs in code with id(1), id(2) etc without clicking position. Is this possible.
JS:
$(function() {
$('button').on('click', function() {
var $sparkLines = $('.sparkLines');
$("#sparkLineContainer").append('<div id="id' + ($sparkLines.length + 1) + '" class="sparkLines">Some Stuff Here</div>');
});
});
HTML:
<div id="sparkLineContainer">
<div class="sparkLines" id="id1">Some stuff here</div>
<div class="sparkLines" id="id2">Some stuff here</div>
<div class="sparkLines" id="id3">Some stuff here</div>
</div>
<button>Add Spark Line</button>
Actually I want to add class to all divs but with id1, id2, id3.
For example:
<div class="addclass" id="id1"></div>
<div class="addclass" id="id2"></div>
Hi you can do that using a counter on your function, Let me use Jquery on this.
function addDiv(){
var counter =0;
$('id').append('div id="' + counter +'"');
counter = counter + 1;
}
This should work.

Dynamically created collapsible-set in jQuery Mobile

Okay, once i see the answer to this, I will feel stupid. I'm certain of that.
I've created this exactly the way I want to before, but I am refactoring my code for a new version right now. I am trying to dynamically create collapsible sets in jQuery Mobile, but my html does not render right.
<div data-role="header">
<h2>Playground</h2>
</div>
<div data-role="content">
<div data-role="button" id="addprimary" data-inline="true">Add 5</div>
<div data-role="collapsible">
<h4>Collapsible</h4>
<form id="makecollapsible">
</form>
</div>
</div>
<div data-role="footer">
<h4>Please, no applause</h4>
</div>
</div>
<script>
$('#addprimary').on('click', function () {
Markup.Collapsible();
});
var Markup = new Object();
Markup.Collapsible = function () {
$('#makecollapsible')
.append($('<div>')
.attr({ 'data-role': 'collapsible-set', 'id': 'primary' })
);
for (i = 0; i < 5; i++) {
($('<div>')
.attr({ 'data-role': 'collapsible', 'data-content-theme': 'c',
'data-collapsed': 'true' })
.html('<h4>' + i +'</h4>'))
.appendTo('#primary');
}
}
</script>
Could somebody please take a look at this http://jsfiddle.net/c2jLY/ and tell me what I have wrong? My <div>s with data-role='collapsible' are not rendering as collapsibles, which is also having an effect on the HTML I am trying to put in them later on.
Help is appreciated, thanks!
Inside Markup.Collapsible function and at the end of it, add the below. For collapsible-set, you need to tell jQM that you're enhancing a .collapsibleset() and combine it with .trigger('create').
$('#makecollapsible').collapsibleset().trigger('create');
Demo
I forgot to mention that when appending items dynamically, call enhancement methods on parent element; doing so, will enhance children elements. Thus, you don't need to use .collapsible().trigger('create') for each collapsible appended.
what i show here is a simple one but working:
<script type="text/javascript">
//dynamically make 10 collapsible items and append them to the collapsible-set
var jj = "SUPER item added..";
$('[data-role="content"]').append('<div id="set" data-role="collapsible-set"></div>');
var count;
for (count=0; count < 10; count++) { // div id should be from id='c0' to 'c9'
$("#set").append('<div id="c' + count + '" data-role="collapsible">');
$("#c" + count.toString()).append('<h3>Adding element_' + count +'</h3>');
$("#c" + count.toString()).append(jj + 'count ' + count + '</div>');
}
// either one is tested working below:
// $('[data-role="content"]').trigger('create');
$( "#set" ).collapsibleset( "refresh" );
</script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<!------------------------page 1 ListView template-->
<div data-role="page" id="page01">
<div data-role="header" data-theme="b" data-position="fixed">
<h2>-- DEMO -- </h2>
</div>
<div data-role="content" id="content">
</div>
</body>

Categories