Detach and append divs/html jquery - javascript

I thought this would be kinda straightforward but i cant wrap my head around this. I got to following html:
<div id="foo">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
<div id="bar">
<div class="test">test1</div>
<div class="test">test2</div>
<div class="test">test3</div>
<div class="test">test4</div>
</div>
I need to grab/detach the div's .test and put/append them into the .item div's. So the first div .test needs to go in the first div .item, the second div .test to the second div .item etc. So it becomes:
<div id="foo">
<div class="item">1<div class="test">test1</div></div>
<div class="item">2<div class="test">test2</div></div>
<div class="item">3<div class="test">test3</div></div>
<div class="item">4<div class="test">test4</div></div>
</div>
Now i found some jquery code and i came to this:
var child = $('#bar').find("div").eq(0);
var parent = $('#foo').eq(0);
child.detach();
parent.append( child );
This works but as suspected, it detaches/appends the first div. Now i need to detach/append them all one by one and from reading a lot of topics, i think i need to put a loop/each in there somewhere but i have no idea how and im not getting any closer after screwing around for hours.
Anyone who can put me in the right direction with this?

You can move all of them easily by just using the append() method and selecting all the divs:
$('#bar').append( $('#foo div') )
/* This is just for showing that the elements actually moved. */
#foo { background:red; }
#bar { background:blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
<div id="bar">
<div class="test">test1</div>
<div class="test">test2</div>
<div class="test">test3</div>
<div class="test">test4</div>
</div>
<div>
Alternatively, if you want to do something with each element, you can use .each():
$('#foo div').each(function(i, elem) {
var $elem = $(elem);
//Do stuff
$('#bar').append($elem);
});
/* This is just for showing that the elements actually moved. */
#foo { background:red; }
#bar { background:blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
<div id="bar">
<div class="test">test1</div>
<div class="test">test2</div>
<div class="test">test3</div>
<div class="test">test4</div>
</div>
<div>

On solution is to get both collections and iterate over one of the collections. Also note that you don't need to use .detach. .append will already do that.
var $fooItems = $("#foo .item");
var $barTests = $("#bar .test");
$fooItems.each(function(index, el) {
$(this).append($barTests.eq(index));
});
Example Fiddle

I think there are two solutions for your issue : .childern() function or usiing jQuery selectors
For example using selector :
$("#bar > div")
or using children() function :
$("#bar").children("div");
also look at this post, you may have your answer here : jQuery - get all divs inside a div with class ".container"

Related

Could I get to an element using two ids?

Here's my code:
<div id='layer1'>
<div id='a'>
<div id='b'>
<div id='layer2'>
<div id='a'>
<div id='b'>
<div id='layer3'>
<div id='a'>
<div id='b'>
I want to try to get the element [a] of layer1.
Could I do this using pure javascript and withOUT jquery and other stuff?
An ID uniquely identifies one single element on the page. The behavior you described is more like "a class" inside of an ID:
document.querySelector("#counter-for-drinks .up-arrow")
and so if you want a different up-arrow, it is:
document.querySelector("#counter-for-burgers .up-arrow")
document.querySelector() is what is similar to jQuery $(" "). It also has the form document.querySelectorAll() for getting all matched elements.
Your HTML is missing closing tags. You can always validate your code here.
Also, you should use class instead of id.
<div id='layer1'>
<div class='a'></div>
<div class='b'></div>
</div>
<div id='layer2'>
<div class='a'></div>
<div class='b'></div>
</div>
<div id='layer3'>
<div class='a'></div>
<div class='b'></div>
</div>
You can use javascript to get elements:
document.querySelector("#layer1 .a")
var firstA = document.querySelectorAll('#layer1 #a');
var nodeString = '';
if (firstA.length > 0) {
for (var i = 0; i < firstA.length; i++) {
nodeString = nodeString + firstA[i].innerText + '<br/>';
}
}
document.getElementById('founded-nodes').innerHTML = nodeString;
#founded-nodes {
color: brown;
}
<div id='layer1'>
<div id='a'>layer1 aaa</div>
<div id='b'>layer1 bbb</div>
</div>
<div id='layer2'>
<div id='a'>layer2 aaa</div>
<div id='b'>layer2 bbb</div>
</div>
<div id='layer3'>
<div id='a'>layer3 aaa</div>
<div id='b'>layer3 bbb</div>
</div>
<div id="founded-nodes"></div>
As all said in above over comments and answers, one must use a single id on the same page, or else the use of classes is a must. But if you want to achieve this, you can have a look at code.

Javascript: Add margin-top to an object, object with other objects is inside object A, multiple objects A on page

I have an object (div) which has four elements (with classes) inside.
What I am trying to do: When height of the element A is lower than 40px then add to element B 20px margin-top.
However there are many objects on the page.
<div class="list">
<div class="block">
<div class="list-name" style="height: 20px">element A</div>
<div class="div1">another div here</div>
<div class="div2">another div here</div>
<div class="product-image-container">element B</div>
</div>
<div class="block">
<div class="list-name" style="height: 50px">element A</div>
<div class="div1">another div here</div>
<div class="div2">another div here</div>
<div class="product-image-container">element B</div>
</div>
(...)
</div>
So far I tried this. Nevertheless it works only if there are only two elements in the div.
$(document).ready(function(){
$('.list-name').each(function(index, obj){
console.log($(obj).height())
if($(obj).height() < 40)
{
$(obj).next('.product-image-container').css('margin-top', 20)
}
});
});
Any help is much appreciated.
Rob
next() only works for the very next element.
Use siblings() instead which includes all elements on same level
$(obj).siblings('.product-image-container').css('margin-top', 20)
Or another commonly used pattern is to look up to a common ancestor and find() within that parent
$(obj).closest('.block').find('.product-image-container').css('margin-top', 20)

How to move several divs up the DOM with jQuery

I would like to move several divs up the DOM with jQuery.
<section>
<div class="title"></div>
<div class="temps"></div>
<div class="list"></div>
</section>
I would like to move all the .list divs after the .title div. How can I do this with jQuery.
This $('.temps').insertAfter('.title'); does not work, it places all the .list after the first .title
I would like to move all the .list divs after the .title div.
You can use each method like this:
$('.list').each(function(){
$(this).insertAfter(
$(this) //.list div
.closest('section') //find parent div section
.find('.title') //find child div
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<div class="title">title</div>
<div class="temps">temps</div>
<div class="list">list</div>
</section>
<section>
<div class="title">title</div>
<div class="temps">temps</div>
<div class="list">list</div>
</section>
<section>
<div class="title">title</div>
<div class="temps">temps</div>
<div class="list">list</div>
</section>
simply try this, demo
$('.list').insertAfter($('.title'));
or
$('.list').insertAfter('.title'); //only selector no object
Try this
$('.list').each(function(){
$(this).prevAll('.title').after($(this));
});
I wouldn't of been anble to get this working without #Bhojendra Nepal help in his answer above, and while his solution worked in his code snippit it did not work on my application. In the end the below worked for me.
jQuery('.list').each(function(){
jQuery(this).insertAfter(jQuery(this).parent().find('.title'));
});

jQuery closest class selector

<div class="wrap">
<div class="Level2">Click me</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level2">Click me</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level2">Click me</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level2">Click me</div>
<div class="Level3">Information</div>
</div>
jQuery
$('.Level2').click(function(){
$('.Level2').closest('.Level3').fadeToggle();
});
I wanted to select the closest level3 to fadeIn and fadeOut, but doesn't work. Is my syntax wrong? online Sample :http://jsfiddle.net/meEUZ/
Try .next() instead of .closest() that traverses through the ancestors of the DOM element.
Working Demo
Also you should use $(this) rather than $('.Level2') else it'll select ALL the .Level2 rather than the clicked one.
You can also go for something like this - $(this).closest('.wrap').find('.Level3').fadeToggle();.
jQuery's .closest() method doesn't select sibling selectors, but parents. Looks like you're looking for the .siblings() method.
$('.Level2').click(function(){
$(this).siblings('.Level3').fadeToggle();
});
closest travels up the dom tree. it won't find something thats a sibling. you can use a find on a parent to achieve this
$('.Level2').click(function(){
$(this).parent().find('.Level3').fadeToggle();
});
Yes, There are many method avaiable in Jquery to find closest of the DOM element
$('.Level1').click(function(){
$(this).next('.Level3').fadeToggle();
});
$('.Level2').click(function(){
$(this).closest('.wrap').find('.Level3').fadeToggle();
});
$('.Level4').click(function(){
$(this).parent().find('.Level3').fadeToggle();
});
$('.Level5').click(function(){
$(this).siblings('.Level3').fadeToggle();
});
.level{background:Red;width:200px;height:40px;}
.Level3{background:blue;width:300px;height:50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="Level1 level">Click me()sing next)</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level2 level">Click me(Using closest)</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level4 level">Click me(Usingh Parent)</div>
<div class="Level3">Information</div>
</div>
<div class="wrap">
<div class="Level5 level">Click me(Using Sibiling)</div>
<div class="Level3">Information</div>
</div>
Yes! closest starts the DOM search from the selector you pass to it, and goes upwards the DOM hierarchy, searching through the parents/ancestors. Use siblings or next instead.
Like this:
$('.Level2').click(function(){
$(this).siblings('.Level3').fadeToggle();
});
Get a clear idea from the following code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$(".add").on("click", function () {
var v = $(this).closest(".division").find("input[name='roll']").val();
alert(v);
});
});
</script>
<?php
for ($i = 1; $i <= 5; $i++) {
echo'<div class = "division">'
. '<form method="POST" action="">'
. '<p><input type="number" name="roll" placeholder="Enter Roll"></p>'
. '<p><input type="button" class="add" name = "submit" value = "Click"></p>'
. '</form></div>';
}
?>

jquery : dynamic events how to achieve

What is the best way to do this dynamic events linking between divs in jquery.
my HTML page:
<html>
<body>
<div id="parent1"></div>
<div id="parent2"></div>
<div id="parent3"></div>
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
</body>
</html>
for each clicked parent i want to .toggle its child
Example :: if parent2 clicked, .toggle will be applied on child2 only
my parents and childs divs are dynamically created so their number is not static, i think .live should be used here, but i have no idea how to achieve that.
Thanks
This should do it, using the rel attribute to note link. You could also do the same thing by parsing the ID and so on, but I find this solution more semantic (if it means something) :
<html>
<body>
<div id="parent1" class="parents" rel="child1"></div>
<div id="parent2" class="parents" rel="child2"></div>
<div id="parent3" class="parents" rel="child3"></div>
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
</body>
</html>
jQuery(function(){
jQuery(".parents").live("click", function(){
jQuery("#"+jQuery(this).attr("rel")).toggle();
});
});
This will work with your current structure (another option is to extract the number, same general idea):
$("[id^=parent]").live('click', function(){
var childId = this.id.replace('parent', 'child');
$('#' + childId).toggle();
});
Using the startsWith selector and slightly modded ID values, because the underscore character eliminates the need for a regex:
<div id="parent_1" class="parents"></div>
<div id="parent_2" class="parents"></div>
<div id="parent_3" class="parents"></div>
<div id="child_1"></div>
<div id="child_2"></div>
<div id="child_3"></div>
$("div[id^=parent]").click(function() {
$('#child_' + $(this).attr('id').split('_')[1]).toggle();
});
I also like #Kobi's approach.
Use a class for these divs and use the class selector.
$(".divclass").live ( "click" , function() {
$(this).find("yourchildelementselector").toggle();
});
If its a parent child relation then better put the child divs inside the parent element.
<div id="parent1" class="parent"><div id="child1" class="child"></div></div>
<div id="parent2" class="parent"><div id="child2" class="child"></div></div>
<div id="parent3" class="parent"><div id="child3" class="child"></div></div>
and you can call the click event as
$("div.parent").live ( "click" , function() {
$(this).find("div.child").toggle();
});

Categories

Resources