jQuery basic: How to create a loop with this structure? - javascript

This is a really simple question but I'm not sure how to search for it on the internet.
I have an empty <div id="wrap"></div> that needs to end up looking as following:
<div id="wrap>
<div class="container">
<div class="apples"></div>
</div>
<div class="container">
<div class="banana"></div>
</div>
<div class="container">
<div class="orange"></div>
</div>
<div class="container">
<div class="grapes"></div>
</div>
</div>
In jquery I have:
$(#wrap).html(''); // need this bit
var fruitArray = ['apples','banana','orange','grapes'];
for (fruit in fruitArray) {
$('<div class="'+fruitArray[fruit]+'"></div>').appendTo('#wrap').doSomething();
}
Because I need the div with the fruitArray class to do something, I can't just wrap it around with the container class:
$('<div class="container"><div class="'+fruitArray[fruit]+'"></div></div>').appendTo...
How can I go about generating the container class in this situation?

The .wrap method returns the original set of elements for chaining purposes.
$('<div class="'+fruitArray[fruit]+'" />')
.appendTo('#wrap')
.wrap('<div class="container" />')
.doSomething();

Try this:
var fruitArray = ['apples','banana','orange','grapes'];
for (fruit in fruitArray) {
$('<div class="' + fruitArray[fruit] + '"></div>').appendTo('#wrap').wrap('<div class="container"></div>');
}
Example fiddle

var fruitArray = ['apples','banana','orange','grapes'];
for (fruit in fruitArray) {
$('<div class="'+fruitArray[fruit]+'" />').wrap('<div class="container" />').appendTo('#wrap').doSomething();
}
OR you can also do it like
var fruitArray = ['apples','banana','orange','grapes'];
for (fruit in fruitArray) {
$('<div class="'+fruitArray[fruit]+'" />').appendTo('#wrap').doSomething().wrap('<div class="container" />');
// this will work if the doSomething is a jquery/plugin method that is using chaining (usually they do)
}

Related

How to hide an item?

var r1=Math.floor(Math.random()*255)
var g1=Math.floor(Math.random()*255)
var b1=Math.floor(Math.random()*255)
$(".color1").click(function (){
$(this).css("background", "rgb(" + r1 + "," + g1 + "," + b1 + ")")
})
$(document).ready(function () {
$(document).on('click', function (event) {
$target = $(event.target);
$target.addClass('clicked');
});
})
var numItems
var getfirstclass
var getsecondclass
$('div').click(function saveclassnames(){
var getfirstclass=$(this).attr('class')
console.log(getfirstclass)
var getsecondclass=$(this).attr('class')
console.log(getsecondclass)
getfirstclass===null
getsecondclass===null
})
$('div').click(function remove(){
var numItems = $('.clicked').length
if(numItems===2 && getfirstclass === getsecondclass){
$('.clicked').css('opacity', '0')
}
else{
$('.clicked').css('background', 'black')
}
})
<body>
<div class="container">
<div class="row">
<div class="color1"></div>
<div class="color2"></div>
<div class="color3"></div>
<div class="color4"></div>
</div>
<div class="row">
<div class="color5"></div>
<div class="color3"></div>
<div class="color1"></div>
<div class="color6"></div>
</div>
<div class="row">
<div class="color7"></div>
<div class="color6"></div>
<div class="color8"></div>
<div class="color5"></div>
</div>
<div class="row">
<div class="color7"></div>
<div class="color8"></div>
<div class="color4"></div>
<div class="color2"></div>
</div>
</div>
</body>
I am trying to make a game called "Memory" (if 2 flipped cards are same, the cards will disappear, but if the cards are not the same, they will flip back). But there is a difference between the original one). I am using random colors instead of card pictures, but I cannot make <div> elements with the same background-color disappear, or flip back if they are not the same. Can someone explain to me why this code does not work?
Thanks.
opacity: 0; hiding generates a lot of space although the element is not visible.
background: black; – the element needs to blend in with the background, otherwise it will not work (technically it won't work)
You can either do this:
$('yourItem').css({
display: 'none'
});
Or, the "simplest way to hide an element":
$('yourItem').hide();
For more information see https://api.jquery.com/hide/
You could use
display: none
If that messes with other stuff, use
visiblity: hidden;

How to loop and set inner content of DOM elements in jQuery and JavaScript?

I'm trying to loop through divs and set the content of a div inside the outer div. I tried this.
Here is the HTML div's I want to loop through and I want to set the content of div with class content-detail with the value for its attribute data-form data.
//the javascript code I used is this
$(function($) {
for (var i of $(".item .content-detail")) {
var container = document.querySelector($(i)[0]);
var formData = $(i).attr("data-formdata");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="item">
<div class="down-div"> </div>
<div class="detail">
<h4>Detail</h4>
<div id="div_" class="content-detail" data-formdata="my Item">
</div>
<div class="text-center">
<button class="btn btn-blue center"> SET !</button>
</div>
</div>
</div>
<div class="item">
<div class="down-div"> </div>
<div class="detail">
<h4>Detail</h4>
<div id="div_" class="content-detail" data-formdata="my Item">
</div>
<div class="text-center">
<button class="btn btn-blue center"> SET !</button>
</div>
</div>
</div>
But am stuck at this point var container = document.querySelector($(i)[0]);
I don't know how to get the jquery selector of that current div to a variable.
This may need some tweaks, but it should be close...
$(function ($) {
$(".item .content-detail").each(function(index, element) {
element.text($(element).attr("data-formdata"))
})
});
Take a look at the .each() method
$(function($) {
for (var i of $(".item .content-detail")) {
//var container = document.querySelector($(i)[0]);
var container = i;
var formData = $(i).attr("data-formdata");
}
});
I just needed the element
If you want to set the content of each DIV, you don't need a for loop. The .text() method takes a callback function, and it will be called on each element that matches the selector. The returned value is used as the new content.
$(".item .content-detail").text(function() {
return $(this).data("formdata");
});
This works.
$(function($) {
$(".item .content-detail").text(function(){
return $(this).attr("data-formdata");
})
});
Can you not just use JS like this:
[UPDATED]
function test() {
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
var divsSub = divs[i].getElementById("div_").querySelectorAll(".content-detail");;
for (var iS = 0; iS < divsSub.length; iS++) {
var x = divsSub[iS].getAttribute("data-formdata");
divsSub[iS].innerHTML = x;
}
}
}

jquery not getting class name of elements

I have the following code but for some reason jQuery does not pick the elements class name, I understand that if the element has more than one class calling .attr('class') won't return them but the .hasClass('class-name') should be able to identify if the element has the class name.
My problem is that jquery returns class name as undefined(I got this from the line commented.).
How can I make the all other div children of the #parent, that do not have class the-one to have a yellow background.
$(document).ready(function()
{
var j = $('#parent> div').size();
for(var i =0;i<j;i++)
{
//alert($('#parent> div').children().eq(i).attr('class'));
if(!$('#parent> div').children().eq(i).hasClass('the-one'))
{
$('#parent> div').children().eq(i).css('background','yellow')
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div class = "one the-one">one</div>
<div class = "two">two</div>
<div class = "three">Three</div>
<div class = "four">Four</div>
</div>
The children() call is redundant as none of the div elements have any child elements. Remove that and the code works:
$(document).ready(function() {
var j = $('#parent> div').size();
for (var i = 0; i < j; i++) {
//alert($('#parent> div').eq(i).attr('class'));
if (!$('#parent> div').eq(i).hasClass('the-one')) {
$('#parent> div').eq(i).css('background', 'yellow')
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent">
<div class="one the-one">one</div>
<div class="two">two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>
Also note that you can tidy the logic in your JS using each() with the this keyword to reference the element in the loop:
$('#parent > div').each(function() {
if ($(this).hasClass('the-one'))
$(this).css('background', 'yellow')
});
The problem is $('#parent> div') returns the div children of #parent so calling children() again does not return any elements.
You can use a simple jQuery selector instead of a loop like
$(document).ready(function() {
$('#parent> div:not(.the-one)').css('background', 'yellow')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent">
<div class="one the-one">one</div>
<div class="two">two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>
But you can just use css for this, no need to use jQuery
#parent> div:not(.the-one) {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent">
<div class="one the-one">one</div>
<div class="two">two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>
$(document).ready(function() {
$('#parent > div').each(function(){
var classtheone = $(this).hasClass('the-one');
if(!classtheone){
$(this).css('background-color', 'yellow')
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div class = "one the-one">one</div>
<div class = "two">two</div>
<div class = "three">Three</div>
<div class = "four">Four</div>
</div>
Try this way
Why not try a simpler method?:
$("#parent > div").not(".the-one").css("background", "yellow");
More info about jQuery's .not method...
Try this
$("#parent div").each(function(){
var me=$(this);
if(me.hasClass("the-one")) { me.css({"background-color" : "yellow"}); }
})
As written already in other answers, your children() call is the problem, I suggest using the following solution with each() as it is simpler
$(document).ready(function()
{
$('#parent div').each(function( i ) {
if ( !$(this).hasClass('the-one')) {
$(this).css('background','yellow');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div class = "one the-one">one</div>
<div class = "two">two</div>
<div class = "three">Three</div>
<div class = "four">Four</div>
</div>

tSort on jQuery object

I'm trying to sort the results of a jQuery selection with tSort.
HTML:
<div sort="2"></div>
<div sort="3"></div>
<div sort="1"></div>
<div sort="4"></div>
<div sort="6"></div>
<div sort="5"></div>
Javascript:
<script>
$sort_order = $('div').tsort({attr:'sort'});
</script>
I want the result to be: 1,2,3,4,5,6 in the jQuery object, not yet inserted into the page.
Is this possible with tSort, or should I write my own algorithm?
It is easier to do it if there is a wrapper of all the div elements.
HTML:
<div id="wrapper">
<div sort="2">2</div>
<div sort="3">3</div>
<div sort="1">1</div>
<div sort="4">4</div>
<div sort="6">6</div>
<div sort="5">5</div>
</div>
Javascript (with jQuery):
var $wrapper = $('#wrapper');
$wrapper.find('div').sort(function (a, b) {
return +a.getAttribute('sort') - +b.getAttribute('sort');
})
.appendTo($wrapper);
Working demo.
In response to #Tim's comment, you can place the elements that do not have the sort attributes at the back of the wrapper element easily, even without jQuery.
Assuming that this is your HTML:
<div id="wrapper">
<div style="color:red;">red color, without sort attribute</div>
<div style="color:red;" sort="7">red color (sort attribute=7)</div>
<div sort="2">2</div>
<div sort="3">3</div>
<div sort="1">1</div>
<div sort="4">4</div>
<div sort="6">6</div>
<div sort="5">5</div>
</div>
You can place the element(s) that do not have the sort attribute by having this as your Javascript:
// As shown earlier above,
var $wrapper = $('#wrapper');
$wrapper.find('div').sort(function (a, b) {
return +a.getAttribute('sort') - +b.getAttribute('sort');
})
.appendTo($wrapper);
// New code to add:
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++) {
if(divs[i].getAttribute('sort') == null || divs[i].getAttribute('sort') == undefined) {
divs[i].parentNode.appendChild(divs[i]);
}
}
Working demo.
clone it before using .tsort
$sort_order = $('div').clone().tsort({attr:'sort'});
DEMO

Using jQuery, how to find the index of an element amongst its siblings of a specified CSS class

Given the following HTML:
<div class="component">
<div class="component">
<div class="component">
</div>
</div>
<div class="component">
<div class="somethingelse">
</div>
<div class="component">
</div>
<div class="component">
<input type="button" value="Get Path" onclick="showPath(this)" />
</div>
</div>
</div>
I'm trying to write the function showPath so that it returns the index of the parent div in relation to its siblings of class component. So in the above sample, I would like the function to return 1.
I've got this far, but it returns 2; I don't know what to do to ignore the div of class somethingelse
function showPath(element) {
var component = $(element).closest('.component');
alert(component.index());
}
A quick and simple extension for jQ to turn this process into a method:
$.fn.getIndex = function(){
var index = $(this).parent().children().index( $(this) );
return index;
}
Run this on document.ready or wrap it in a function and run it that way (probably cleaner).
Usage is as simple as
var index_for_element = $('.thing-you-want-index-for').getIndex();
Try this(haven't tested):
function showPath(element) {
var component = $(element).closest('.component');
alert(component.parent().find(".component").index(component));
}
You can do this.
$('input').click(function() {
var component = $(this).closest('.component');
alert(component.parent().children(".component").index(component));
})
Check working example at http://jsfiddle.net/Qzk6A/2/

Categories

Resources