loop the .append() with selector as variable - javascript

I am trying to loop the .append() function in order to change the selector each time with different value. But, I don't know the syntax for the selector in order to meet my target. So, how to change it? Thanks so much!
Ka Ho
<script type="text/javascript">
var a=3;
for (var i=0;i<a;i++) {
$i.append(i);
}
</script>
<div class="0"></div> // expected: display 0
<div class="1"></div> // expected: display 1
<div class="2"></div> // expected: display 2

You can also use a function as argument to append, might be cleaner and possibly faster in your case:
$('div').append(function() {
return this.className;
});
http://jsfiddle.net/sSVL8/

<script type="text/javascript">
var a=3;
for (var i=0;i<a;i++) {
$("."+i).append(i); //this is what you need
}
</script>
<div class="0"></div> // expected: display 0
<div class="1"></div> // expected: display 1
<div class="2"></div> // expected: display 2

First of all numeric class and ids are not supported that much as you think it is.
Update your HTML to something like this
<div class="box-0"></div>
<div class="box-1"></div>
<div class="box-2"></div>
Then you can use the script provided by deadlock in his answer.
var a=3;
for (var i=0;i<a;i++) {
$(".box-"+i).append(i); //this is what you need
}

Related

console.log($('.divs').click(<function>)) shows an array of divs ... does the click method return the object it acts on?

console.log($('.divs').click(<function>))
This shows an array of divs.
Does the click method return the object it acts on?
It is just something basic - maybe someone can say more.
That $() returns the array of elements with that selector makes natural sense. But $(<selector>).click(<function definition>) - just defines what should happen on each element of $(<selector>) when it is clicked - why does it also "return" the array of elements?
Here is also a fiddle for the above http://jsfiddle.net/jy7kpL6f/
or here - HTML/CSS/jQuery
var addclass = 'color';
var $cols = $('.divs').click(function(e) {
$cols.removeClass(addclass);
$(this).addClass(addclass);
});
var $cols2 = $('.divs');
console.log($('.divs').click(function(e) {
$cols.removeClass(addclass);
$(this).addClass(addclass);
}));
.color {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divs">
1st Div
</div>
<div class="divs">
2nd Div
</div>
<div class="divs">
3rd Div
</div>
<div class="divs">
4th Div
</div>
click() returns all selected elements like many other jQuery functions.
This can be handy to chain functions like this:
$(".divs")
.click(callback1)
.hover(callback2)
...etc
Yes, it does. It returns the elements due to something called chaining. It enables such calls as:
$('div').addClass('on').removeClass('off');

jQuery clicking function - get ID of this

I've written my own jQuery clicking function, but for an unkown reason, it doesn't work. I get error on line 4.
for (var i = 1;i<=3;i++){
$("#Block"+i).click(function(){
$(this).effect("shake", function(){
if (this == "#Block3"){
window.open('contact.html','blank');//open link link in a new page
}
});
});
}
Could you please help me?
Explanation
this on line 4 returns (or is) an object, it is a DOM element (such as <div> or something like that) You can't compare object this and string "#Block3".
These two things are very different. It is like comparing pears and apples.
Take a look at JavaScript Data Types I think, it could help you.
Documentation
See the documentation of this object.
Getting ID of an element How can I get the ID of an element using jQuery?
Edit of your code
You have to get the ID of the object (this) and then compare it with the string "Block3"
for (var i = 1; i <= 3; i++) {
$("#Block" + i).click(function() {
$(this).effect("shake", function() {
if (this.id == "Block3") {
window.open('contact.html', 'blank'); //open link link in a new page
}
});
});
}
Edit of your code 2
jQuery is here to help you to do less of code. Take a while to look at some tutorials.
Your code could be shortened to something like this
$('.blocks-container').on('click', '.block', function() {
$(this).effect('shake', function() {
if (this.id == 'Block3')
window.open('contact.html', 'blank'); //open link link in a new page
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blocks-container">
<div id="Block1" class="block">Block1</div>
<div id="Block2" class="block">Block2</div>
<div id="Block3" class="block">Block3</div>
<div id="Block4" class="block">Block4</div>
<div id="Block5" class="block">Block5</div>
</div>
With unlimited number of "Blocks". See Rory's answer!
.click vs .on
Also please learn to use
$('.blocks-container').on('click', '.block', function() {});
Instead of
$('.block').click(function() {});
Explanation here I think, that you will understand later.
Edit of your code 3
Or you can base your function on "Block" div index (= number of place under the parent element) instead of index. So you don't have to use ID for each of blocks.
$('.blocks-container').on('click', '.block', function() {
$(this).effect('shake', function() {
if ($(this).index('.block') == 2)
window.open('contact.html', 'blank'); //open link link in a new page
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blocks-container">
<div class="block">Block1</div>
<div class="block">Block2</div>
<div class="block">Block3</div>
<div class="block">Block4</div>
<div class="block">Block5</div>
</div>
Love jQuery. Peace!
this in your code is a DOMElement. When coerced to a string it will never match #Block3, hence your if condition never hits.
Assuming you're trying to match the id of a specific element, then you just need to compare against the id property of this:
(var i = 1; i <= 3; i++){
$("#Block" + i).click(function(){
$(this).effect("shake", function(){
if (this.id === "Block3") {
window.open('contact.html', 'blank');
}
});
});
}
Also note that it would be much better practice to put a common class on all the #BlockX elements and use a single event handler on all of them:
$('.block').click(function() {
$(this).effect("shake", function(){
if (this.id === 'Block3')
alert('you clicked block3!');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div id="Block1" class="block">Block1</div>
<div id="Block2" class="block">Block2</div>
<div id="Block3" class="block">Block3</div>
<div id="Block4" class="block">Block4</div>
<div id="Block5" class="block">Block5</div>

Get part of CSS class as string?

Say I had the following 4 divs:
<div class="mine-banana"></div>
<div class="mine-grape"></div>
<div class="mine-apple"></div>
<div class="orange"></div>
I've discovered I can use the following JQuery selector to get the 3 "mine" divs, but I can't quite figure out how to return all the fruits that are "mine" :)
$('[class*=" mine-"]').each(function() {
var fruit = $(this).????
});
DEMO
The best way to accomplish that is to refactor your html, as #Ian pointed it out, for example :
<div class="mine" data-mine-fruit="banana"></div>
<div class="mine" data-mine-fruit="grape"></div>
<div class="mine" data-mine-fruit="apple"></div>
<div class="orange"></div>
The JS code is straightforward now :
var fruits = $('.mine').map(function () {
return $(this).attr('data-mine-fruit')
});
If you still want to use your current code, here is a regex-based code
var fruits = []
$('[class*=" mine-"], [class^="mine-"]').each(function() {
fruits.push( this.className.match(/[^a-z0-9_-]?mine-([0-9a-z_-]+)/i)[1] );
})
which really works

Accessing jQuery IDs with for loop

I have a simple problem and hopefully a simple answer.
So, I have a JSON file which I'm utilizing that has a ton of data in it. I'm trying to make a slideshow with such data, which is built, but I'm having trouble appending the proper information to the slides without hard coding everything.
My idea is to use a for loop to target specific IDs (slides), but I can't for the life of me figure out how to target each item for the loop.
I was thinking something like this, which is not working at all lol.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$(function() {
for (var i=0; i<10; i++) {
$('#slide(i)').append("<p>Hello World</p>");
}
})();
</script>
</head>
<body>
<div id="slide0"></div>
<div id="slide1"></div>
<div id="slide2"></div>
<div id="slide3"></div>
<div id="slide4"></div>
<div id="slide5"></div>
<div id="slide6"></div>
<div id="slide7"></div>
<div id="slide8"></div>
<div id="slide9"></div>
</body>
As far as actually targeting individual slides, any syntax I try I can't get it to go.
Any help is appreciated!
Use string concatenation
jQuery(function ($) {
for (var i = 0; i < 10; i++) {
//use string concatenation
$('#slide' + i).append("<p>Hello World</p>");
}
});//also there is no () here... it is not a IIFE... it is a callback registration which will be invoked by jQuery when dom ready is fired
Demo: Fiddle

jQuery: Loop iterating through numbered classes?

I looked at the post jQuery: Loop iterating through numbered selectors? and it didn't solve my problem, and didn't look like it was truly an answer that works.
I have a list of <h3> tags that are titles to questions, and there are answers below in a <p>. I created classes for each Q & A like so:
<h3 class="sec1">Question:</h3><p class="view1">Answer...</p>
<h3 class="sec2">Question:</h3><p class="view2">Answer...</p>
<h3 class="sec3">Question:</h3><p class="view3">Answer...</p>
I used the following jQuery loop to reduce redundacy for my 21 questions.
$(document).ready(function () {
for (var i = 1; i < 21; i++) {
var link = ".sec" + i;
var content = ".view" + i;
$(link).click(function () {
$(content).toggle("fast");
});
}
});
But it isn't working for all Q & A sets, only the last one. i.e.: It works for the first set if I set the max value to 2 (only looping once). Please advise. Thanks
While I agree with #gaffleck that you should change your approach, I think it is worth while to explain how to fix the current approach.
The problem is that the click function does not get a copy of the content variable but instead has a reference to that same variable. At the end of the loop, the value is .view20. When any element is clicked it read that variable and gets back .view20.
The easiest way to solve this is to move the code into a separate function. The content variable within this function is a new variable for every call of the function.
function doIt(i){
var link = ".sec" + i;
var content = ".view" + i;
$(link).click(function () {
alert(content);
});
}
$(document).ready(function () {
for (var i = 1; i < 21; i++) {
doIt(i);
}
});
http://jsfiddle.net/TcaUg/2/
Notice in the fiddle, if you click on a question the alert has the proper number. Optionally, you could make the function inline, though I find the separate function in most cases to be a bit cleaner.
http://jsfiddle.net/TcaUg/1/
A much easier way to do this, would be this:
$(document).ready(function(){
$("h3").click(function(){
$(this).next("p").toggle("fast");
});
});
This is also safer in that you can add/remove questions and answers in the future and you won't have to update the function.
Wrap your questions in a more logical structure to create a proper scope for your questions-block:
<div id="questions">
<div class="question">
<h3 class="sec1">Question:</h3><p class="view1">Answer...</p>
</div>
<div class="question">
<h3 class="sec2">Question:</h3><p class="view2">Answer...</p>
</div>
<div class="question">
<h3 class="sec3">Question:</h3><p class="view3">Answer...</p>
</div>
</div>
Now iterate through it like this:
$(function() {
$('#questions .question h3').click(function(){
$(this).parent().find('.answer').toggle('fast');
});
});

Categories

Resources