So I'm basicaly just trying move element from one node to an other.
I create a fragment and then append to it my children elements.
const fragment = document.createDocumentFragment();
let sortedElements = [...document.querySelectorAll('.product')].sort((a,b) => b.dataset.blockSize - a.dataset.blockSize ); //Select elements
sortedElements.forEach((e) => {
console.log(e) //My 4 children displayed
fragment.appendChild(e)
});
console.log(fragment.children); //Only Two children in it
fragment.childNodes.forEach((el) => {
document.querySelector("#appendThere").appendChild(el);
})
<div class="product" data-object-size="4">Product 1</div>
<div class="product" data-object-size="2">Product 2</div>
<div class="product" data-object-size="1">Product 3</div>
<div class="product" data-object-size="1">Product 4</div>
<div id="appendThere"></div>
Am I missunderstanding how does fragments works ?
It's strangely working on snippet...
Even partialy working on my computer But its getting stranger.
I think there is a change between the moment I print my variable and I explore it.
You are mutating fragment.childNodes while iterating over it, which is causing the unexpected behavior. You just need to append fragment rather than appending each of it's children.
For example (fixed the element data attributes to correspond to the sort js in your example):
const fragment = document.createDocumentFragment();
const sorted = [...document.querySelectorAll('.product')].sort((a,b) => {
return b.dataset.blockSize - a.dataset.blockSize;
});
sorted.forEach((elem) => {
fragment.appendChild(elem);
});
document.querySelector('#destination').appendChild(fragment);
<div class="product" data-block-size="3">Product 2</div>
<div class="product" data-block-size="1">Product 3</div>
<div class="product" data-block-size="4">Product 1</div>
<div class="product" data-block-size="1">Product 4</div>
<div id="destination"></div>
Or, without using a document fragment (may not be a big performance difference if you are working with a limited number of elements).
const destination = document.querySelector('#destination');
const sorted = [...document.querySelectorAll('.product')].sort((a,b) => {
return b.dataset.blockSize - a.dataset.blockSize;
});
sorted.forEach((elem) => {
destination.appendChild(elem);
});
<div class="product" data-block-size="3">Product 2</div>
<div class="product" data-block-size="1">Product 3</div>
<div class="product" data-block-size="4">Product 1</div>
<div class="product" data-block-size="1">Product 4</div>
<div id="destination"></div>
Related
I want to get the first 3 elements in a div, so e1, e2 and e3:
<div id="parent">
<div id="e1">element 1</div>
<div id="e2">element 2</div>
<div id="e3">element 3</div>
<div id="e4">element 4</div>
</div>
I want to do this with jQuery. What's the best way to achieve this?
Actually you can do this with nth-child pseudo-class with functional notation. So this will work like:
:nth-child(-n+3)
Represents the first three elements. [=-0+3, -1+3, -2+3]
Where the functional notation represents elements in a list whose indices match those found in a custom pattern of numbers, defined by An+B, where:
A is an integer step size,
B is an integer offset,
n is all positive integers, starting from 0.
So your final code would be something like:
const elements = document.querySelectorAll('#parent > div:nth-child(-n+3)')
elements.forEach(element => {
console.log(element.id)
})
<div id="parent">
<div id="e1">element 1</div>
<div id="e2">element 2</div>
<div id="e3">element 3</div>
<div id="e4">element 4</div>
</div>
But if you want to stick with jQuery itself you can use jQuery :lt() instead. Where jQuery( ":lt(index)" ) Select all elements at an index less than index within the matched set
The output will be something like this:
const elements = $('#parent > div:lt(3)')
jQuery.each(elements, function (index, element) {
console.log(element.id)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
<div id="e1">element 1</div>
<div id="e2">element 2</div>
<div id="e3">element 3</div>
<div id="e4">element 4</div>
</div>
You can use jQuery's .each() function and a little conditional if statement with the function's index...
$('#parent').children().each(function(index){
// To counteract the zero-based index.
index++
if (index < 4) {
console.log(this);
}
});
Example on Codepen
Does anybody have any idea how to create a variable that contains the id of a clicked div?
I want to hide all the #content-wrappers on page load apart from the first one then when the .square has been clicked for it to display the div with the same class as the id that has been clicked, it doesn't make much sense when you write id down but if you look at my fiddle then it should hopefully make sense?
http://jsfiddle.net/alexjamest/Lkaxza22/
$('#content-wrapper').hide();
$(".square").click(function() {
var id_name= $(this).attr(id);
if $('#content-wrapper').hasClass(id_name){
$(this).fadeIn();
}
});
<div id="content-wrapper" class="c1">Content 1</div>
<div id="content-wrapper" class="c2">Content 2</div>
<div id="content-wrapper" class="c3">Content 3</div>
<div id="content-wrapper" class="c4">Content 4</div>
<div id="content-wrapper" class="c5">Content 5</div>
<div id="content-wrapper" class="c6">Content 6</div>
<div id="content-wrapper" class="c7">Content 7</div>
<div id="content-wrapper" class="c8">Content 8</div>
<div class="square" id="c1"></div>
<div class="square" id="c2"></div>
<div class="square" id="c3"></div>
<div class="square" id="c4"></div>
<div class="square" id="c5"></div>
<div class="square" id="c6"></div>
<div class="square" id="c7"></div>
<div class="square" id="c8"></div>
Change your content-wrappers elements so that they contain classes, not ids, since ids should be unique. You can, however, identify your content with some sort of a prefix, like content-:
<div class="content-wrapper" id="content-c1">Content 1</div>
<div class="content-wrapper" id="content-c2">Content 2</div>
<div class="content-wrapper" id="content-c3">Content 3</div>
<div class="content-wrapper" id="content-c4">Content 4</div>
<div class="content-wrapper" id="content-c5">Content 5</div>
<div class="content-wrapper" id="content-c6">Content 6</div>
<div class="content-wrapper" id="content-c7">Content 7</div>
<div class="content-wrapper" id="content-c8">Content 8</div>
Then the following code will work:
$(document).ready(function()
{
$(".content-wrapper").hide();
$(document).on("click", ".square", function()
{
var id = $(this).attr("id");
$("#content-"+id).fadeIn();
});
});
Note the following part
$(".content-wrapper").hide();
which is important, since we're identifying that we wish to hide all elements which contain the class content-wrapper, not the id content-wrapper.
Working Demo.
There are four problems with your code:
$('#content-wrapper').hide(); will only hide the first element with that ID, because IDs have to be unique. Use a common class instead.
var id_name= $(this).attr(id);. id is an undefined variable. You probably want to pass the string "id" instead, or better, just access the property of the DOM element: this.id.
if $('#content-wrapper').hasClass(id_name){ is a syntax error. The condition has to be put in parhenthesis:
if ($('#content-wrapper').hasClass(id_name)) {
However, that alone won't make the condition work, since again, #content-wrapper will only select the first element. Just select the corresponding element by class:
$('.' + this.id).fadeIn();
You can also add .content-wrapper for more granular filtering:
$('.content-wrapper.' + this.id).fadeIn();
Fixed code:
$('.content-wrapper').hide(); // give that class to all elements instead of the ID
$(".square").click(function() {
$('.' + this.id).fadeIn();
});
DEMO
A JQuery-less solution, still with the fade animation.
On load it gets an array of buttons and an array of content wrappers, then it just uses the order to figure out which box to reveal. Will only work with an equal number of buttons and wrappers. I started the wrappers as invisible in the style sheet, so we only have to reveal them. Also remembers which buttons was clicked last and resets its visibility.
<head>
<style>
.content-wrapper{
opacity:0;
transition:opacity 1s ease;/* only showing the normal one, prefixed may be required for portability*/
}
</style>
<script>
window.addEventListener('load',onload,false);
var wrappers;
var buttons;
var last;
function onload(){
wrappers = document.getElementsByClassName('content-wrapper');
buttons = document.getElementsByClassName('square');
var i = buttons.length;
while(i--) // add listener for each button
buttons[i].addEventListener('click',onclick,false);
}
function onclick(){
if(last)wrappers[last].style.opacity = '0.0'; //hide previous
var i = buttons.indexOf(this);
wrappers[i].style.opacity = '1.0'; //show clicked
last = i;
}
</script>
</head>
<body>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='square'></div>
<div class='square'></div>
<div class='square'></div>
<div class='square'></div>
<div class='square'></div>
</body>
How can i wrap exactly half of the div's with another div using jquery or javascript
I have this
<div class="post">1</div>
<div class="post">2</div>
<div class="post">3</div>
<div class="post">4</div>
<div class="post">5</div>
<div class="post">6</div>
I want this
<div class="wrap">
<div class="post">1</div>
<div class="post">2</div>
<div class="post">3</div>
</div>
<div class="wrap">
<div class="post">4</div>
<div class="post">5</div>
<div class="post">6</div>
</div>
Try using this:
var posts = $('.post'),
postCount = posts.length,
postHalf = Math.round(postCount/2),
wrapHTML = '<div class="wrap"></div>';
posts.slice(0, postHalf).wrapAll(wrapHTML); // .slice(0, 3)
posts.slice(postHalf, postCount).wrapAll(wrapHTML); // .slice(3, 6)
This selects all .post, gets the number of elements found then halves that value to get the splitting point. It then uses .slice() to select a specific range of elements and .wrapAll() to wrap each selection in <div class="wrap"></div>.
Here it is working: http://jsfiddle.net/ekzrb/
I have divs with same class, but each 3 are wrapped in a parent div. I can't get the index the way I want it. I am sorry, could anyone help me to get the index as number from 0 to 8.. when i click on any element? despite the parent element.
Here is my full code for your testing.
<div class="more-content">
<div class="post">post 1</div>
<div class="post">post 2</div>
<div class="post">post 3</div>
</div>
<div class="more-content">
<div class="post">post 4</div>
<div class="post">post 5</div>
<div class="post">post 6</div>
</div>
<div class="more-content">
<div class="post">post 7</div>
<div class="post">post 8</div>
<div class="post">post 9</div>
</div>
<script type="text/javascript">
$(function() {
// navigate posts with next/prev buttons
$(".post").click(function(){
alert($(this).index());
});
});
</script>
If i click i get index 0, 1, 2 ..i think because each 3 items are wrapped in parent? I am new with jquery, any help appreciated. what i need is get the index of post with same class.. say post 6 = index 5.. and so on
UPDATE
How can I get the same result if the clicked element is a child anchor in the post div and not the post div directly?
Try index method with this as an argument:
$(".post").click(function() {
alert($(".post").index(this));
});
DEMO: http://jsfiddle.net/Nryf3/
var posts = $('.post').click(function(){
alert(posts.index(this));
});
DEMO: http://jsfiddle.net/paZ2e/
You could loop through all elements tagged post and increment a counter until you find the object you're looking for, like this:
$(".post").click(function() {
var counter = 0;
var that = this;
$(".post").each(function() {
if(that == this) break;
counter++;
}
// counter now equals the index of the post element out of all posts on the page
});
Looking to create Javascript that acts like a filter on a list of divs.
For instance, here's the intended markup...
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>
I want to be able to click on the link for Item 1, and show only Item 1 divs and hide all other divs, click the link of Item 2, and show only Item 2 divs and hide all other divs and so on. I've seen several similar scripts but nothing that seemingly turns divs matching the class on/off in this manner.
This can be done easily in Jquery, following should work for you, but you have to modify your html as following
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>
and javascript as follows
$(document).ready(function(){
$(".link").click(function(e){
$("." + e.currentTarget.id).toggle()
}
});
You can use jQuery's toggle. below is simple example:
$(document).ready(function() {
$('#IDOfLink').click(function() {
$('.class1').toggle("slow");//switch to show/hide when clicked
//hide other div u wish
});
$('#anotherLinkID').click(function() {
$('.class2').toggle("fast");//switch to show/hide when clicked
//hide other div u wish
});
//...etc...
});
Very simple solution:
Filter Item 1
This, ofcourse, will hide all the other div's on page, so you should give the all some other class or put inside another div. Then the code could be:
Filter Item 1
<div id="filtered">
<div class="1"></div>
...
</div>
Set an ID for each link, then assign an onclick event. There you can filter out divs using the clicked link ID.
Something like this (http://jsfiddle.net/pJRek/1/)
Markup:
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
<div class="group_1">Item 1</div>
<div class="group_1">Item 1</div>
<div class="group_2">Item 2</div>
<div class="group_3">Item 3</div>
<div class="group_1">Item 1</div>
<div class="group_4">Item 4</div>
<div class="group_4">Item 4</div>
<div class="group_1">Item 1</div>
<div class="group_5">Item 5</div>
And script:
$(document).ready(function(){
var links = $('.bound');
var divs = $('div');
links.click(function(event){
divs.hide();
divs.filter('.' + event.target.id).show();
});
});
If you setup your HTML as:
<div id="controls">
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
</div>
<div id="items">
<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>
</div>
Then your jQuery code can be as simple as:
$(function(){
$("#controls a").click(function() {
$("#items").find("." + this.id).toggle();
});
});
Of course, you will want to add a visual indication that a filter is toggled on and off.
You may not want to associate the items with each link through id/classes, but instead use jQuery's data storage, depending on your needs.
A working example, tested in firefox, here: http://jsfiddle.net/mwolfetech/GetRV/
Edit: This solution is similar to Anto Binish Kaspar's, mainly differing only in
how the html is modified. I think that the divs given are likely to be a good structure for your document anyway, and eliminates the need for extra classes for control. This is always a design decision--balancing div (for structural division) vs class (for, categories). Additionally, theres no need to extract the id from the event object as jQuery provides the this reference.
Give them all another class (for example item) and then make the click hide all item and show all of the selected value.