How can I dynamically generate a jQuery selector? - javascript

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/

Related

toggle div using for loops

just wondering what went wrong.. i have two div named click_1 and click_2.. and i want to toggle the div named hide corresponding with their numbers.. lets say click_1 with hide_1 and click_2 with hide_2.. but when i ran the code only click_1 is functioning .. what seems to be wrong... newbie here.. recently learned jquery
<div id='click_1'>
<div id='hide_1'></div>
</div>
<div id='click_2'>
<div id='hide_2'></div>
</div>
<script>
function toggle_div(id_A,id_B){
for(var i=0; i<3; i++){
var new_A = id_A + i;
var new_B = id_B + i;
$(new_A).click(function(){
$(new_B).toggle();
});
}
}
toggle_div('click_','hide_');
</script>
The issue is because your id selectors are missing the # prefix:
toggle_div('#click_', '#hide_');
However you should note that you will also need to use a closure for this pattern to work otherwise the new_B element will always be the last one referenced in the for loop.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='click_1'>
click 1
<div id='hide_1'>hide 1</div>
</div>
<div id='click_2'>
click 2
<div id='hide_2'>hide 2</div>
</div>
<script>
function toggle_div(id_A, id_B) {
for (var i = 1; i < 3; i++) {
var new_A = id_A + i;
var new_B = id_B + i;
(function(a, b) {
$(a).click(function() {
$(b).toggle();
})
})(new_A, new_B);
}
}
toggle_div('#click_', '#hide_');
</script>
As you can see this is very verbose, rather complicated and hardly extensible. A much better approach is to use generic classes and DOM traversal to repeat the same logic on common HTML structures.
To achieve this put common classes on the elements to be clicked and the elements to toggle. Then in the single click event handler you can use the this keyword to reference the element which was clicked, then find() the element to toggle within that. Something like this:
$(function() {
$('.click').click(function() {
$(this).find('.hide').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="click">
click 1
<div class="hide">hide 1</div>
</div>
<div class="click">
click 2
<div class="hide">hide 2</div>
</div>
<div class="click">
click 3
<div class="hide">hide 3</div>
</div>
Also note that this pattern means that you can have an infinite number of .click elements with matching .hide content without ever needing to update your JS code.
It is better not to use for loop for click event ! If you have id like that your can handle by that clicked id split ....
$("[id^='click_']").on("click",function () {
$('#hide_'+this.id.split('_')[1]).toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='click_1'>
Click1
<div id='hide_1'>hide1</div>
</div>
<div id='click_2'>
Click2
<div id='hide_2'>hide2</div>
</div>

JavaScript: If condition based on div ID

I'm making a web app for a school project and I'm creating a function for a click event on my ".tile" class. Inside the tile class I have 7 tile IDs; "#tile1", "#tile2" etc. I want to make an 'if' condition to check the ID of the tile clicked e.g. if (ID == "#tile2") {}. Is something like this possible or do I need to make functions for each individual tile? The rest of the function is fine I only need help with the if statement. Sorry if this is really easy I'm fairly new.
It is possible. You can do :
$('.tile').click(function(){
var id = $(this).attr('id');
if(id === 'tile2'){
// do smthing
} else if(id === 'tile3'){
} ...
});
Where $(this) is the clicked element
You could also use a switch case to switch between your id's. See the doc https://www.w3schools.com/js/js_switch.asp
You could attach the click event listener on the class .tile and get the "clicked" tile's id by $(this).attr('id'), please see follow:
$(".tile").click(function(){
let id = $(this).attr('id');
console.log("Clicked on div: " + id);
if(id === "tile3")
console.log("Yes, it's the third");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>What's the third?</p>
<div id="tile1" class="tile">tile 1</div>
<div id="tile2" class="tile">tile 2</div>
<div id="tile3" class="tile">tile 3</div>
<div id="tile4" class="tile">tile 4</div>
<div id="tile5" class="tile">tile 5</div>
I hope it helps you, bye.

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>

jquery toggle visibility if has class

I've collected all my portfolio items into an array as seen here.
function SetPortfolioItems(filter) {
items = $( ".portfolio-item" );
items.toggle("slow");
}
The function parameter is a string class name for example "Print". What I want to do is hide the portfolio items which don't have the class 'filter' and the ones that do, make them visible.
For your question:
What I want to do is hide the portfolio items which don't have the class 'filter' and the ones that do, make them visible.
You can make this:
function SetPortfolioItems(filter) {
var str = filter.toLowerCase();
var invalidItems = $( ".portfolio-item:not(."+str+")");
invalidItems.hide("slow");
var validItems = $( ".portfolio-item." + str );
validItems.show("slow");
}
SetPortfolioItems('filter');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="portfolio-item">item 1</div>
<div class="portfolio-item filter">item 2</div>
<div class="portfolio-item">item 3</div>
<div class="portfolio-item filter">item 4</div>
<div class="portfolio-item">item 5</div>
<div class="portfolio-item">item 6</div>
Use jQuery not() function.
function SetPortfolioItems(filter) {
items = $( ".portfolio-item" );
items.not('.' + filter).hide("slow");
}
Use hasClass by jQuery :
jQuery Docs
function SetPortfolioItems(filter) {
items = $( ".portfolio-item" );
if (items.hasClass(filter)) {
...
} else {
...
}
}

toggling div and adding and removing class

i have some divs i wanna toggle i am able to toggle but unable to remove classes when ever i click on the next div
index.php
<div id="menu_top1" class="menu_top1">LINK 1</div>
<div id="menu_top" class="menu_top">LINK 2</div>
<div id="content_area1" style="display:none;">
THIS IS LINK 1
</div>
<div id="content_area2" style="display:none;">
THIS IS LINK 2
</div>
Jquery.js
$('#menu_top1').click(function() {
$('#content_area1').toggle('slow', function() {
$('.menu_top1').toggleClass('active');
});
});
Here is a Fiddle https://fiddle.jshell.net/kunz/t5u6mcmn/
if you are trying to show corresponding content_area when you click on link and make the link active? you can check this
fiddle
i saw you using same id for multiple elements.just edited them.
still you want same id for all elements(strictly not recommended) check this fiddle
check this updated fiddle
$('.menu_top').click(function() {
var index = $( this ).index() + 1;
console.log(index);
$('[id^="content_area"]' ).hide();
$('#content_area' + index ).toggle('slow', function() {
$('.menu_top').toggleClass('active');
});
});

Categories