I have some code formatted as following:
<div id="section">
<div class="col-xs-6"></div>
<div class="col-xs-6"></div>
<div class="col-xs-6"></div>
<div class="col-xs-6"></div>
<div class="col-xs-6"></div>
<div class="col-xs-6"></div>
<div class="col-xs-6"></div>
</div>
There can be any number (even or odd) of columns in this section.
What I want is for it to be re-formatted like this:
<div id="section">
<div class="row">
<div class="col-xs-6"></div>
<div class="col-xs-6"></div>
</div>
<div class="row">
<div class="col-xs-6"></div>
<div class="col-xs-6"></div>
</div>
<div class="row">
<div class="col-xs-6"></div>
<div class="col-xs-6"></div>
</div>
<div class="row">
<div class="col-xs-6"></div>
</div>
</div>
Here is my attempt to do so:
for (var x = 0; x < $('#section').children().length; x+=2) {
var firstSection = $('#section').children().eq(x);
if ($('#section').children().length >= x + 1) {
var secondSection = $('#section').children().eq(x + 1);
var finalSection = '<div class="row">' + firstSection.parent().html() + secondSection.parent().html() + '</div>';
secondSection.remove();
}
else {
var finalSection = '<div class="row">' + firstSection.html() + '</div>';
}
firstSection.remove();
$('#section').append(finalSection);
}
If anyone wants some extra fun, you could try allowing this to handle variable column widths as well! (Although I don't need that for my project).
Hers is an example that loops through the columns, similar to what you are attempting now.
It uses find(), append() and clone() to accomplish this task. As an added feature I wrapped it into a function that accepts the row size as an argument.
//breaks up the section into rows of size 'rowSize', 2 by default.
function breakitup(rowSize = 2) {
var $section = $("#section"); //get the section
var $row = $("<div class='row'>"); //make a template for a row
var cols = $section.find("div"); //get the columns
var working; //tmp variable for the current row
for (var i = 0; i < cols.length; i++) {
if (i % rowSize == 0) working = $row.clone(); //clone the template when appropriate
$(working).append(cols[i]); //add the column to the row
if ($(working).children().length == rowSize)
$section.append(working); //add the row to the section as appropriate
}
$section.append(working); //add the last row
}
//call our fancy function
breakitup();
.row {
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="section">
<div class="col-xs-6">test</div>
<div class="col-xs-6">test2</div>
<div class="col-xs-6">test3</div>
<div class="col-xs-6">test4</div>
<div class="col-xs-6">test5</div>
<div class="col-xs-6">test6</div>
<div class="col-xs-6">test7</div>
</div>
You can use .wrapall(), .add() and :even selector:
$('#section > div:even').each(function(idx, ele) {
$(ele).add($(this).next()).wrapAll($('<div/>', {class: 'row'}));
});
console.log($('#section').html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="section">
<div class="col-xs-6">1</div>
<div class="col-xs-6">2</div>
<div class="col-xs-6">3</div>
<div class="col-xs-6">4</div>
<div class="col-xs-6">5</div>
<div class="col-xs-6">6</div>
<div class="col-xs-6">7</div>
</div>
Related
I am trying to get first letter of firstname and lastname from a div and paste it in another div but it is pasting the same value in all divs and not taking unique value from each div.
Working Fiddle: https://jsfiddle.net/bv7w8dxg/1/
Issue Fiddle: https://jsfiddle.net/bv7w8dxg/
var takword = $('.nameholder').text().split(' ');
var text = '';
$.each(takword, function () {
text += this.substring(0, 1);
});
$('.avatarholder').text(text);
Markup
`
John Doe
<div class="main-holder">
<div class="nameholder">Kyle Davis</div>
<div class="avatarholder"></div>
</div>
<div class="main-holder">
<div class="nameholder">Seim Seiy</div>
<div class="avatarholder"></div>
</div>
<div class="main-holder">
<div class="nameholder">Momma Boy</div>
<div class="avatarholder"></div>
</div>`
You are using class selectors, which selects all elements with the given class name. That's why you have all the elements set with same value
You need to wrap your elements then process each row independently
I updated your code snippet to demonstrate this:
$('.row').each(function() {
var takword = $('.nameholder', this).text().split(' ');
var text = '';
$.each(takword, function () {
text += this.substring(0, 1);
});
$('.avatarholder', this).text(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="nameholder">John Doe</div>
<div class="avatarholder"></div>
</div>
<div class="row">
<div class="nameholder">Kyle Davis</div>
<div class="avatarholder"></div>
</div>
<div class="row">
<div class="nameholder">Seim Seiy</div>
<div class="avatarholder"></div>
</div>
<div class="row">
<div class="nameholder">Momma Boy</div>
<div class="avatarholder"></div>
</div>
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 3 years ago.
When I change from querySelector to querySelectorAll I get undefined. I know that the spelling for the class name is correct. So, I posted the rest of the code assuming that there is something else that I must be missing.
//TAKES INPUT FORM AND PLACES TEXT ON CARD
var input1 = document.querySelector('.form1');
var input2 = document.querySelectorAll('.form2');
var textOnCard = document.getElementById('btn');
btn.addEventListener('click', function() {
document.getElementById('flashcard__front').innerHTML = input1.value
document.getElementById('flashcard__back').innerHTML = input2.value
});
//FUNCTION THAT ALLOWS CARD TO ROTATE
var flashcard = document.querySelector('.flashcard');
flashcard.addEventListener('click', function() {
flashcard.classList.toggle('flip');
});
//CREATES A NEW INPUT FIELD
var inputHtml = '<div class="container mt-5"><div class="row"><div class="col-lg-12 text-center"><form id="form" action=""><div><input type="text" class="form1">'+ ' ' + '<input type="text" class="form2">' + ' ' + '</div></form></div></div>'
var addInputField = document.getElementById('addInputField');
addInputField.addEventListener('click', function() {
textOnCard.insertAdjacentHTML("afterend", inputHtml)
});
//make array apppear on screen
var flashcardFront = [];
var flashcardBack = [];
var number = 0;
var rightArrow = document.getElementById('rightArrow');
var leftArrow = document.getElementById('leftArrow');
textOnCard.addEventListener('click', function(){
flashcardFront.push(input1.value);
flashcardBack.push(input2.value);
flashcard__front.innerHTML = flashcardFront[0];
flashcard__back.innerHTML = flashcardBack[0];
console.log(Array.from(input1));
})
rightArrow.addEventListener('click', function(){
if (number < flashcardFront.length - 1 && number < flashcardBack.length - 1){
number++;
} else {
number = 0
}
console.log(number);
document.getElementById('flashcard__front').innerHTML = flashcardFront[number];
document.getElementById('flashcard__back').innerHTML = flashcardBack[number];
});
leftArrow.addEventListener('click', function(){
if (number > flashcardFront.length && number > flashcardBack.length){
number--;
} else {
number = 0
}
console.log(number);
document.getElementById('flashcard__front').innerHTML = flashcardFront[number];
document.getElementById('flashcard__back').innerHTML = flashcardBack[number];
});
<div class="container mt-5">
<div class="row">
<div class="col-lg-12 text-center">
<input type="text" class="form1">
<input type="text" class="form2">
<button class="btn btn-primary text-center" id="btn">SUBMIT</button>
</div>
</div>
</div>
<div class="container mt-5">
<div class="row">
<div class="col-lg-12 text-center">
<input type="text" class="form1">
<input type="text" class="form2">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<button class="btn btn-primary" id="addInputField">ADD A NEW INPUT</button>
</div>
</div>
</div>
<div class="container mt-5">
<div class="row">
<div class="col-lg-12">
<div class="flashcard">
<div class="flashcard__side flashcard__side--front">
<h1 id="flashcard__front" class="text-center m-3"></h1>
</div>
<div class="flashcard__side flashcard__side--back">
<h1 id="flashcard__back" class="text-center m-3"></h1>
</div>
</div>
</div>
</div>
</div>
<div class="container mt-5">
<div class="row">
<div class="col-lg-12">
<h3 id="testField" class="pl-5"></h3>
</div>
</div>
<div class="row">
<div class="col-md-6">
<i class="fas fa-arrow-left" id="leftArrow"></i>
</div>
<div class="col-md-6">
<i class="fas fa-arrow-right" id="rightArrow"></i>
</div>
</div>
</div>
For context, I am trying to recreate the flashcard feature from quizlet.com for practice.
Because .querySelectorAll() returns a node-list (an array-like container object), not an individual node. So, this line:
var input2 = document.querySelectorAll('.form2');
Creates a collection of all the elements with a class of form2.
Later, when you do this:
document.getElementById('flashcard__back').innerHTML = input2.value
You are saying that you want to get the value of the collection, but the collection doesn't have a value property, individual nodes do, so the flashcard__back element gets .innerHTML of undefined.
You'll have to identify which node within the list you want by passing an index to the node-list and then you can work with properties/methods of nodes.
I want to define and set multiple div and its ID dynamically like this:
function add_div() {
div_number = 'div' + number.toString();
document.getElementById("all").innerHTML += "<div id=div_number > </div>" ;
++number;
}
But the name of all the IDs are identical: div+ number where number is the last value of number
By that, I mean, if number = 20 for 20 calls of add_div()
I want to get: div1 , div2 , div3 , ... div20
But I get div20, div20 , ... div20
function add_div(number) {
for (var i = 1; i <= number; i++) {
var div = document.createElement('div');
div.id = 'div' + i;
document.getElementById("all").appendChild(div);
}
}
add_div(20);
<!-- Outputs-->
<div class="all">
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<div class="div4"></div>
<div class="div5"></div>
<div class="div6"></div>
<div class="div7"></div>
<div class="div8"></div>
<div class="div9"></div>
<div class="div10"></div>
<div class="div11"></div>
<div class="div12"></div>
<div class="div13"></div>
<div class="div14"></div>
<div class="div15"></div>
<div class="div16"></div>
<div class="div17"></div>
<div class="div18"></div>
<div class="div19"></div>
<div class="div20"></div>
</div>
I'm trying to create a grid table using jQuery.
So instend of adding those elements into html page:
<div id="grid" class="gridTable">
<div class="row">
<span class="cell head"></span>
<span class="cell head"></span>
<span class="cell head"></span>
</div>
<div class="row">
<span class="cell"></span>
<span class="cell"></span>
<span class="cell"></span>
</div>
<div class="row">
<span class="cell"></span>
<span class="cell"></span>
<span class="cell"></span>
</div>
<div class="row">
<span class="cell"></span>
<span class="cell"></span>
<span class="cell"></span>
</div>
</div>
I want to add only the grid container:
<div id="grid" class="gridTable"><div>
and inside of this container to add my rows dynamically using jQuery append() or other method:
<div class="row">
<span class="cell head"></span>
<span class="cell head"></span>
<span class="cell head"></span>
</div>
repeating each time I want. I have tried something like:
$('.gridTable').append( $("<div></div>").addClass('row') );
but I don't know how to add .cell child of appended elements.
See full html code in fiddle:
Store appended element in variable and use it after append. To do this work, you need to write new element in selector and use .appendTo() to appending element.
var row = $('<div></div>').addClass("row").appendTo(".gridTable");
row.append("<span class='cell head'>col</span");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grid" class="gridTable"></div>
If you want to create all row and column of table dynamicaly, see bottom code.
for (var i = 0; i < 4; i++){
var row = $('<div></div>').addClass("row").appendTo(".gridTable");
for (var j = 0; j < 3; j++){
if (i == 0)
row.append("<span class='cell head'>head</span");
else
row.append("<span class='cell'>col</span");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grid" class="gridTable"></div>
You can create a function that returns a row object with specified number of cells and call it for each row:
TIP:
Adjust the function as you like (e.g. It can take a parameter for cell classes)
var grid = $('#grid');
/**
* Returns a jQuery object of a row
* param cells {number} The number of cells
*/
function getRow(cells, customClass) {
var c = '';
for (var i=0;i<cells;i++) {
c += '<span class="cell ' + customClass + '">Cell</span>';
}
var row = $('<div class="row">' + c + '</div>');
return row;
}
// Add 5 rows
var rows = 5;
for (var r=1;r<=rows;r++) {
var customClass = (r == 1) ? 'head' : '';
grid.append(getRow(3, customClass));
}
.cell {
display:inline-block;
padding:5px 10px;
border:1px solid #d8d8d8;
}
.head { font-weight:bold }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="grid" class="gridTable"></div>
I have 2 divs, #col1 and #col2, that I need to generate some divs with fruit names in there.
So far I have:
var fruitArray = ['apples','banana','orange','grapes'];
for (fruit in fruitArray) {
$('<div class="'+fruitArray[fruit]+'"></div>').appendTo('#col1').doSomething();
$('<div id="'+fruitArray[fruit]+'"></div>').appendTo('#col2').doSomething();
}
Which turns out like:
<div id="#col1">
<div class="apples"></div>
<div class="banana"></div>
<div class="orange"></div>
<div class="grapes"></div>
</div>
<div id="#col2">
<div id="apples"></div>
<div id="banana"></div>
<div id="orange"></div>
<div id="grapes"></div>
</div>
How do I randomize the array so it looks something like:
<div id="#col1">
<div class="orange"></div>
<div class="apples"></div>
<div class="orange"></div>
<div class="grapes"></div>
</div>
<div id="#col2">
<div id="grapes"></div>
<div id="orange"></div>
<div id="apples"></div>
<div id="banana"></div>
</div>
Simple shuffle extension:
Array.prototype.shuffle = function() {
var shuffledArray = [];
while (this.length) {
shuffledArray.push(this.splice(Math.random() * this.length, 1)[0]);
}
while (shuffledArray.length) {
this.push(shuffledArray.pop());
}
return this;
}
Use it like
var fruitArray = ['apples','banana','orange','grapes'].shuffle();
for (var i = 0; i < fruitArray.length; i++) {
$('<div class="'+fruitArray[i]+'"></div>').appendTo('#col1').doSomething();
$('<div id="'+fruitArray[i]+'"></div>').appendTo('#col2').doSomething();
}