Reposition elements in html with jquery - javascript

I can't figure how to achieve this in the best way:
Let's say I have:
<div class="parent">
<div class="child"></div>
</div>
<div class="parent">
<div class="child"></div>
</div>
<div class="parent">
<div class="child"></div>
</div>
And I want to move every 'child' right after it's parent.
<div class="parent"></div>
<div class="child"></div>
<div class="parent"></div>
<div class="child"></div>
<div class="parent"></div>
<div class="child"></div>
How can I achieve this?
Update: Also, how can i exclude the parents that have certain attributes? For example, I need to exclude those that have data-anchor=2 and data-anchor=3 I can't figure out how to do this.

$(".parent").each(function(){
$(this).after($(".child", this));
});
JSFiddle: https://jsfiddle.net/TrueBlueAussie/onsb12jx/
Note: $(".child", this) is just a shorter version of $(this).find(".child")
Excluding elements can use either .not() or :not() or a filter:
e.g. using .not()
$(".parent").not('[data-anchor=2],[data-anchor=3]').each(function(){
$(this).after($(".child", this));
});
or using :not pseudo selector
$(".parent:not([data-anchor=2],[data-anchor=3])").each(function(){
$(this).after($(".child", this));
});
or using a filter() function
$(".parent").filter(function(){
return $(this).data('anchor') == "2" || $(this).data('anchor') == "3";
}).each(function(){
$(this).after($(".child", this));
});

You can achieve this by looping over the .child elements and using insertAfter() to place them after their closest parent .parent element:
$('.parent .child').each(function() {
$(this).insertAfter($(this).closest('.parent'));
});
Example fiddle

Use
$(".parent").each(function() {
$(this).after($(this).find(".child"));
});
after() will help you to position the element after the selected element

You can use .after(fn) method with a function as an argument to return the desired behavior, a benefit of it is not to use a loop explicitly, This way it will do this for you internally:
$('.parent').after(function() {
return $('.child', this);
});
.parent{border:solid red 3px;}
.child{border:solid 3px green; margin:3px 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div class="child">child</div>
parent
</div>
<div class="parent">
<div class="child">child</div>
parent
</div>
<div class="parent">
<div class="child">child</div>
parent
</div>

You can use detach method to do that like so:
$(".parent").each(function() {
$(this).after($(this).find(".child").detach());
});
Here is the JSFiddle demo
You can check the structure by Inspecting element of the age :)

Related

Selecting a parent class from a child class when there are multiple div's of same parent class

There are four parent div's with same class and all of them have a child with class 'child'. Now the question is, Let's say I click on the First parent div's Child div(First Child) and I want to have some effect on it's parent i.e 'First Parent' to be effected only. Due to being similar class' all parent div's will be effected.
Here's the HTML
<div class="parent"> //First Parent
<div class="child"></div> //First Child
</div>
<div class="parent">
<div class="child"></div>
</div>
<div class="parent">
<div class="child"></div>
</div>
<div class="parent">
<div class="child"></div>
</div>
Here's the JQuery
$('.child').on('click',function(){
$(this).parent('.parent').css({
'display':'none';
});
});
Clicking on child element will effect all parent div's with class "parent". Either I can give them all separate classes then write onClick() method for all of them but that is not a proper solution.
You can do
$(this).parent().hide();
if you want to hide the parent of the clicked div
Use closest('.class')
$('.child').click(function() {
$(this).closest('.parent').css('display':'none');
});
I Updated my answer !
Your answer is correct and a good practice, I don't see what the issue here is.
The only change you could do $(this).parent('.parent').hide(); instead of using the jQuery css method.
try this code
$(document).ready(function() {
$('.child').click(function() {
$(this).parent().css('display', 'none');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div class="child">first</div>
</div>
<div class="parent">
<div class="child">second</div>
</div>
<div class="parent">
<div class="child">third</div>
</div>
<div class="parent">
<div class="child">fourth</div>
</div>
$('.child').on('click',function(){
$(this).closest('.parent').css({
'display':'none'
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent"> //First Parent
<div class="child">div 1</div> //First Child
</div>
<div class="parent">
<div class="child">div 2</div>
</div>
<div class="parent">
<div class="child">div 3</div>
</div>
<div class="parent">
<div class="child">div 4</div>
</div>
alterate your JS as follow:
$('.child').on('click',function(){
$(this).parent().css({
'display':'none'
});
});
For me, on click of a div, it hides its parent. Not others.
By the way, you had a ";" after 'none' which is invalid as this is a object, and accepts only either nothing or a comma.
see https://jsfiddle.net/n66sdgdz/
Okay, so lots of answers here with "try this" or other examples.
First off, your code actually works, as you can see here:
Fiddle
However, there was one error in you code. This being the ; at the end of your 'display':'none';
There should be no ; inside a javascript object.
$(document).ready(function() {
$('.child').on('click',function(){
$(this).closest('.parent').css('display','none');
});
});
OR
$('.child').on('click',function(){
$(this).parent('.parent').eq(0).css('display','none');
});
https://jsfiddle.net/t9wxbLs8/

Getting the selector, not the handler

HTML:
<div id="div1">
<div class="close">close</div>
</div>
<div id="div2">
<div class="close">close</div>
</div>
jQuery:
$('.close').on('click', '#div1, #div2', function(){
console.log ( $(this) ); // .close
});
If I have multiple elements with close buttons, how do I get the parent element as this and not the button?
So if I click the .close on #div1, I need #div1 as this to work with it.
By instinct, I would look to closest, which takes a selector as a param:
var selector = '#div1, #div2';
$('.close').on('click', selector, function(){
console.log ( $(this).closest(selector) ); // .close
});
.closest will return a jQuery object representing first node that matches the selector. It starts with the current object and continues to .parent() until it finds a match
since the element is a child of the element you want to reference, use a parent selector.
$(this).parent().hide()
Most of the time we would use a class on the element and use closest to select it.
$(this).closest('.msg').hide()
$('.close').on('click', function(){
$(this).closest(".msg").hide();
});
.msg{
.border: 1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" class="msg">
<div class="close">close</div>
<p>test 1</p>
</div>
<div id="div2" class="msg">
<div class="close">close</div>
<p>test 2</p>
</div>
You actually don't need any selector, just a .closest("div").
If you want to be a bit more specific like "The closest ID starts with div" than you could do like:
$('.close').on('click', function(){
$(this).closest("[id^='div']").fadeOut();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<div class="close">close1</div>
</div>
<div id="div2">
<div class="close">close2</div>
</div>
Or, by doing it the way you started you could use the event.delegateTarget -
which refers to the actual selector-delegators $('#div1, #div2')
$('#div1, #div2').on('click', '.close', function(event) {
$(event.delegateTarget).fadeOut();
});
// or use also for brevity:
// $("[id^='div']").on(...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<div class="close">close1</div>
</div>
<div id="div2">
<div class="close">close2</div>
</div>

Keep only the first three divs

I own a div and within it thousands of others, but I like to keep only the first 3, how to make it work with jquery? Exemple:
<div class="owner">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div> -> DELETE
<div class="child"></div> -> DELETE
<div class="child"></div> -> DELETE
<div class="child"></div> -> DELETE
[...]
</div>
Use :gt selector along with .hide() or .remove():
$('.owner .child:gt(2)').hide();
or
$('.owner .child:gt(2)').remove()
All those jquery solutions do work. But if you also want to do it the CSS way, you can simply do:
.owner .child:nth-child(1n+4) { display: none; }
Try using slice()
$('.owner .child').slice(3).remove();
Yeah, as Milind wrote, you can remove them by :gt selector.
But there is another way to do it:
$(document).ready(function(){
var index = $(".child").length;
while (index--) {
if(index > 2){
($('.child')[index]).remove();
}
}
});
This way is more simple to understand.
I've attached JSFiddle example to the post.

How to count div's of one class, that are children of container div's of one class?

I would like to count the number of ('.child') in each container and append a sentence with the count inside each container.
<div class='container'>
<div class='child'></div>
<div class='child'></div>
<div class='child'></div>
<div class='child'></div>
</div>
<div class='container'>
<div class='child'></div>
<div class='child'></div>
</div>
How would you do that? Would you need id's or can it be done with just classes?
I want to find a clean way of doing it.
Thanks a lot in advance
$('.container').each(function(i, obj){
var children = $(this).find('.child').length;
$('<p>' + children + ' elements.</p>').appendTo( $(this) );
});
use .length to get count of its source
example...
alert($('.container').children().length);
check this fiddle
You don't need additional thing give the above html structure
$('.container').each(function(){
$(this).prepend('<label> No of children:'
+$(this).find('div.child').size()
+'</label>');
});
Here is a simple example that should handle what you are looking for
jQuery
<script>
$(function(){
$('.container').each(function(){
var count=0,child=$(this).find('.child');
if(child.length>0) {
count++;
child.each(function(){
$(this).text('This is child number '+count);
count++;
});
}
});
});
</script>
HTML
<div class="container">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
<div class="container">
<div class="child"></div>
<div class="child"></div>
</div>

jQuery: If all children have same class

How do I check if all children, or all selectors, have same class?
The class is unknown...
<script>
$(document).ready(function() {
var symbols = $("div:first-child").attr("class");
if ($("div").hasClass(symbols).length == 3) {
console.log("same");
};
});
</script>
<div class="john"></div>
<div class="john"></div>
<div class="john"></div>
This doesn't work... :-/
$("div").not('.john').length
If any of the divs are not class john this will find them, then you check the length and if it's not zero then some exist.
This is a problem:
$("div:first-child").attr("class")
It will return the entire class string, but the div could have more than one class, and all will be returned. But when you check with either my code or hasClass you can only send in one class, not a bunch together.
HTML:
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
jQuery:
if ($(".parent").children().length == $(".parent").children(".child").length) {
alert("wooo all the things have teh same class");
}

Categories