swap 2 div's index using pure javascript - javascript

I have a parent div and it has 9 same div's am trying to swap two div's index. Following is my code:
HTML:
<div id="cont" class="container">
<div class="no">1</div>
<div class="no">2</div>
<div class="no">3</div>
<div class="blank"></div>
<div class="no">4</div>
<div class="no">5</div>
<div class="no">6</div>
<div class="no">7</div>
<div class="no">8</div>
</div>
now I want to swap say 5th and 6th indexed elements. I have no clue how to do that in JavaScript. I know there is function called .index() but how to do that in pure JS.

Here's one implementation: http://jsfiddle.net/x8hWj/2/
function swap(idx1, idx2) {
var container = document.getElementById('cont');
// ditch text nodes and the like
var children = Array.prototype.filter.call(
container.childNodes,
function(node) {
return node.nodeType === 1;
}
);
// get references to the relevant children
var el1 = children[idx1];
var el2 = children[idx2];
var el2next = children[idx2 + 1];
// put the second element before the first
container.insertBefore(el2, el1);
// now put the first element where the second used to be
if (el2next) container.insertBefore(el1, el2next);
else container.appendChild(el1);
}
This starts by getting a list of all element child nodes, then uses insertBefore to rearrange them.

Related

Html selector returns an html collection and I don't know how to get to the element I need to make changes on

I have 2 divs: 1 on the left half of the page (A), one on the right (B). When hovering over a certain element of the right section, I want something to be displayed over the left one.
I did this using the following approach:
<div className="A">
<div className="hidden-div1">DIV 1</div>
<div className="hidden-div2">DIV 2</div>
<div className="hidden-div3">DIV 3</div>
</div>
<div className="B">
<div className="base-div1">
<h2 onMouseOver={this.mouseOver} onMouseOut={this.mouseOut}>Project 1</h2>
</div>
</div>
mouseOver(e){
const hiddenDiv1 = document.querySelector(".hidden-div1");
hiddenDiv1.style.display = "block";
}
mouseOut(e){
const hiddenDiv1 = document.querySelector(".hidden-div1");
hiddenDiv1.style.display = "none";
}
Problem is, considering I have 3 different hidden-divs and 3 different base-divs, I wanted to make 2 universal mouseOver and mouseOut functions for all of them. The way I tried it, is this:
mouseOver(e){
let hiddenDivName = "hidden-div" + e.target.className.slice(-1);
let hiddenDivSelector = document.getElementsByClassName(hiddenDivName);
hiddenDivSelector.style.display = "block";
}
but it returns "Cannot set property 'display' of undefined".
I tried console logging hiddenDivSelector and it shows an HTML collection and I don't know how to get my element. I've tried reading about it and visiting other questions but I couldn't apply anything to my situation
Event target returns a reference to DOM element. On DOM elements we can use getAttribute method and replace all non-digit characters by ''; result may be used to search DOM and iterate over returned array;
mouseOver(e){
let hiddenDivName = "hidden-div" + e.target.getAttribute('class').replace(/\D/g, '');
let hiddenDivSelector = document.getElementsByClassName(hiddenDivName);
Array.from( hiddenDivSelector ).forEach(el => el.style.display ) = "block";
}

How to re-Order html child elements in Dom based on id value

I have a parent div with some child elements. I want to re-order child elements based on two id values. for example 1,4. It means to grab the item with id 1 and insert it above the item with id 4.
<div class="parent">
<div id="1">First</div>
<div id="2">Second</div>
<div id="3">Third</div>
<div id="4">Fourth</div>
<div id="5">Fifth</div>
</div>
Making a drag and drop component for react. And this is what i have tried
const element = document.getElementById('1') //dragStart
const targetElement = document.getElementById('4') //dragEnter
const parent = document.querySelector('.parent') // drop
parent.insertBefore(element, targetElement)
But problem is when i grab the first element and want to put it on the bottom (last child). It fails to do so. How to put a child element after last child with insertBefore() method?
Don't know how you are using insertBefore() but there should not be any issues:
Update: The issue could be that your code is running before the DOM is fully loaded. You can wrap your code with DOMContentLoaded:
<script>
document.addEventListener('DOMContentLoaded', (event) => {
const element = document.getElementById('1') //dragStart
const targetElement = document.getElementById('4') //dragEnter
const parent = document.querySelector('.parent') // drop
parent.insertBefore(element, targetElement)
});
</script>
<div class="parent">
<div id="1">First</div>
<div id="2">Second</div>
<div id="3">Third</div>
<div id="4">Fourth</div>
<div id="5">Fifth</div>
</div>
Placing the first element as the last element using nextSibling:
<script>
document.addEventListener('DOMContentLoaded', (event) => {
const parentNode = document.querySelector('.parent');
const element = document.getElementById('1') //dragStart
const targetElement = document.querySelector('.parent').lastElementChild //get last child
parentNode.insertBefore(element, targetElement.nextSibling);
});
</script>
<div class="parent">
<div id="1">First</div>
<div id="2">Second</div>
<div id="3">Third</div>
<div id="4">Fourth</div>
<div id="5">Fifth</div>
</div>
Note: This answers the original question. The question has now been edited to reference React. You wouldn't use the following in a React project. You'd reorder the state that the DOM represents, and then let React handle updating the DOM.
You're right to use insertBefore:
function moveElement(move, before) {
// Get the element to move
const elToMove = document.getElementById(move);
// Get the element to put it in front of
const elBefore = document.getElementById(before);
// Move it
elBefore.parentNode.insertBefore(elToMove, elBefore);
}
function moveElement(move, before) {
const elToMove = document.getElementById(move);
const elBefore = document.getElementById(before);
elBefore.parentNode.insertBefore(elToMove, elBefore);
}
setTimeout(() => {
moveElement("1", "4");
}, 800);
<div class="parent">
<div id="1">First</div>
<div id="2">Second</div>
<div id="3">Third</div>
<div id="4">Fourth</div>
<div id="5">Fifth</div>
</div>
Side note: I suggest avoiding having id values that start with digits. Although they're perfectly valid HTML and they work just fine with getElementById, they're a pain if you need to target them with CSS, because a CSS ID selector (#example) can't start with an unescaped digit. For instance, document.querySelector("#1") fails. You have to escape the 1 with a hex sequence, which isn't terrifically clear: document.querySelector("#\\31") (the characters \, 3, and 1: 0x31 = 49 = the Unicode code point for 1).

How do I loop through HTML DOM nodes?

I want to loop through a nested HTML DOM node, as shown below:
<div id="main">
<div class="nested-div-one">
<div class="nested-div-two">
<div class="nested-div-three">
</div>
</div>
</div>
<div class="nested-div-one">
<div class="nested-div-two">
<div class="nested-div-three">
</div>
</div>
</div>
</div>
How would I do this using Javascript to loop through every single one of the dividers?
I am guessing OP was not specific for DIV elements, here's a more dynamic approach:
So first you wanna get the first container, in your case it's:
var mainEl = document.getElementById('main');
Once you have that, each DOM element has a .children property with all child nodes. Since DOM is a tree object, you can also add a flag to achieve recursive behavior.
function visitChildren(el, visitor, recursive) {
for(var i = 0; i < el.children.length; i++) {
visitor(children[i]);
if(recursive)
visitChildren(children[i], visitor, recursive);
}
}
And now, let's say you want to change all div backgrounds to red:
visitChildren(mainEl, function(el) { el.style.background = 'red' });
You can use vanilla javascript for this
document.querySelectorAll('div').forEach(el => {
// el = div element
console.log(el);
});

Find distance between elements in the DOM

There is a root element in the DOM tree and there is another element inside this root element nested somewhere. How do I calculate how nested is this another element inside the root element?
What I would like to know is essentially how many times I have to get the parent element of the nested element until I get to the root element. So I can solve this problem by iterating on the parents until I get to the root element, like in this fiddle.
const first = document.getElementById('search-target-1');
let parent = first.parentElement;
let level = 0;
do {
parent = parent.parentElement;
level++;
}
while (!parent.classList.contains('root'))
console.log(`The first element is ${level} levels deep inside the root div.`);
const second = document.getElementById('search-target-2');
parent = second.parentElement;
level = 0;
do {
parent = parent.parentElement;
level++;
}
while (!parent.classList.contains('root'));
console.log(`The second element is ${level} level deep inside the root div.`);
<div class="root">
<div class="first-level">
<div class="second-level" id="search-target-1">
<!-- How deep is this element? -->
</div>
</div>
<div class="first-level"></div>
<div class="first-level">
<div class="second-level">
<div class="third-level" id="search-target-2">
<!-- And this one? -->
</div>
</div>
</div>
</div>
Is there a better way of achieving this? I am looking for a javascript api to get the same result.
The element.matchesSelector does not solve my problem, as I know the target element is inside the root element, but I don't know how deep it is.
You could use jQuery's .parentsUntil() function to accomplish this:
var searchDistance_1 = $("#search-target-1").parentsUntil(".root").length; // 1
var searchDistance_2 = $("#search-target-2").parentsUntil(".root").length; // 2
That gives you the number of parents in between the child and root you are looking for. If you're looking for the number of jumps up the hierarchy needed to get to the parent, you can just add 1.
If you need to do this in vanilla JS, you could look through the source code for this function on GitHub.
Your code works, but as Niet the Dark Absol said you need to take care of cases where the descendent isn't a descendent, e.g.
function getLevel(parent, child) {
let level = 0;
while (child && parent != child) {
level++;
child = child.parentNode;
}
return child? level : null;
}
var parent = document.getElementById('parent');
var child = document.getElementById('child');
var notChild = document.getElementById('notChild');
console.log(getLevel(parent, child)); // 3
console.log(getLevel(parent, notChild)); // null
<div id="parent">
<div>
<div>
<div id="child"></div>
</div>
</div>
</div>
<div id="notChild"></div>
Without the guarding condition to stop when the loop runs out of parnetNodes, it will throw an error if child isn't a descendant of parent.

Get Nth parent of multiple elements

How can I get the the Nth parent of multiple elements?
Right now I do it like this:
var winners = THUMBNAILS.find(".tournament-winner:contains(" + filter + ")");
var filteredThumbnails = winners.parent().parent().parent().parent().clone();
this does work.
But when I try to do it like:
var filteredThumbnails = winners.parents().eq(3).clone();
It only gets the thumbnail (great grandfather) of just one element in the winners variable.
Is there any easier way to get Nth parent of multiple elements?
You can use .add()
Create a new jQuery object with elements added to the set of matched elements.
//Create empty object
var filteredThumbnails = $();
//Iterate and target parent
winners.each(function(){
filteredThumbnails.add($(this).parents().eq(3).clone());
});
write a .map() or .forEach() function on the winners array.
example:
filteredThumbnails = winners.map(winner => winner.parent().parent().parent().parent().clone());
It would be a lot easier if you shared your html.
As i am not sure what you are trying to achieve...but
Another way of getting up multiple parent levels of the element you are targeting,
which doesn't have a unique name would be like below. which will traverse up until it finds a parent which has an id which starts with "parent".
winners.parents("[id^=parent]")
Although i would give them a generic css class to travel up to rather than this.
You can also use filter on return value of parents.
$.parents return an array.
Let's say you have the following HTML and you want to get divs with ids parentN. which is the third parent. After that you can convert the elements to an array. Alternatively, you can create a function like this and use it in different places.
then you have to get every fourth element of the parents
function getNthParents(obj, N) {
return obj.parents().filter(index => !((index + 1) % N)).toArray();
}
nthParents = getNthParents($('.thumbnail'), 3)
console.log(nthParents)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent1'>
<div>
<div>
<div class='thumbnail'>
</div>
</div>
</div>
</div>
<div id='parent2'>
<div>
<div>
<div class='thumbnail'>
</div>
</div>
</div>
</div>
<div id='parent3'>
<div>
<div>
<div class='thumbnail'>
</div>
</div>
</div>
</div>

Categories