jQuery closest class selector - javascript

<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>';
}
?>

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.

How to get the value in element child when click a div outside element parent JQuery

Sorry my english bad, for example I have 2 columns, every column when click div.open-model will show a model have a value is h3.title, I used jQuery but i cannot get value h3.title every column
$(document).ready(function() {
$('.open_modal').click(function(e) {
var h3title = $(this).find('.parent .title').html();
console.log('h3title');
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<h3 class="title">Title1</h3>
</div>
<div class="open-model">Open model</div>
<div class="parent">
<h3 class="title">Title2</h3>
</div>
<div class="open-model">Open model</div>
Try prev().
var h3title = $(this).prev('.parent').find(".title").text();
And after fixing other errors
$(document).ready(function() {
$('.open-model').click(function(e) {
var h3title = $(this).prev('.parent').find(".title").text();
console.log(h3title);
e.preventDefault();
});
});
You've got several issues here:
The class on the element is open-model so your selector of open_modal is incorrect
find() looks for child elements, yet the target you want to find is a child of a sibling, so you need prev().find() instead
h3title is a variable, so you don't need to wrap it in quotes when passing it as an argument to console.log().
Try this:
$(document).ready(function() {
$('.open-model').click(function(e) {
e.preventDefault();
var h3title = $(this).prev('.parent').find('.title').text();
console.log(h3title);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<h3 class="title">Title1</h3>
</div>
<div class="open-model">Open model</div>
<div class="parent">
<h3 class="title">Title2</h3>
</div>
<div class="open-model">Open model</div>
spelling of selector is wrong on click
use .prev() instead of .find()
$('.open-model').click(function(e) {// fix selector
var h3title = $(this).prev('.parent').find('.title').html();//use prev()
console.log(h3title);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<h3 class="title">Title1</h3>
</div>
<div class="open-model">Open model</div>
<div class="parent">
<h3 class="title">Title2</h3>
</div>
<div class="open-model">Open model</div>
Change it to
$(document).ready(function(){
$('.open-modal').click(function(e){
e.preventDefault();
var h3title = $(this).prev().find('.title').text();
console.log('h3title');
});
});
In the example below we are getting the the previous DOM element and as we can see in the structure we want to get the inner text of its child element.
$('.open-model').on('click', function(){
console.log($(this).prev().children().text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<h3 class="title">Title1</h3>
</div>
<div class="open-model">Open model</div>
<div class="parent">
<h3 class="title">Title2</h3>
</div>
<div class="open-model">Open model</div>

if one item is clicked, remove the other items?

I'm learning Javascript and jQuery and I'm stuck at this one problem. Let's say my code looks like this:
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
Now, if i click one of the div's, i want the other ones to disappear.
I know, I could create 4 functions for each one of them with on.click hey and display none with how , are and you. But is there a easier way? I bet there is, with classes maybe?
Thanks for responding!
Use siblings to get reference to its "brothers".
Given a jQuery object that represents a set of DOM elements, the .siblings() method allows us to search through the siblings of these elements in the DOM tree and construct a new jQuery object from the matching elements.
$('div').click(function(){
$(this).siblings().hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
Or you can hide all the other div which not the clicked element using not
Remove elements from the set of matched elements.
$('div').click(function() {
$('div').not(this).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
You can just hide siblings() of clicked div.
$('div').click(function() {
$(this).siblings().fadeOut()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey">hey</div>
<div id="how">how</div>
<div id="are">are</div>
<div id="you">you</div>
Yeah there are some easier ways and I could tell a one from it,
Set a common class to all the elements that you are gonna target,
<div class="clickable" id="hey"> hey </div>
<div class="clickable" id="how"> how </div>
<div class="clickable" id="are"> are </div>
<div class="clickable" id="you"> you </div>
And you have to bind a single click event by using a class selector,
$(".clickable").on("click", function(){ });
Now use the .siblings() functions to hide the required elements,
$(".clickable").on("click", function(){
$(this).siblings(".clickable").hide();
});
But using a toggle instead of hide would sounds logical,
$(".clickable").on("click", function(){
$(this).siblings(".clickable").toggle();
});
Since you can do the same operation over all the elements.
You can use not to avoid element and this will indicate current instance.
$(document).ready(function(){
$("div").on("click",function(){
$("div").not(this).hide("slow");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
Assign a class to each of the elements:
<div id="hey" class='sth'> hey </div>
<div id="how" class='sth'> how </div>
<div id="are" class='sth'> are </div>
<div id="you"class='sth' > you </div>
And write a js function onclick.
Remove class 'sth' from 'this' element in this function
Hide all elements with class 'sth' $('.sth').hide();
For this example - you don't need to add any further selectors to target the div's although in reality - this solution wwould cause all divs on the page to be affectecd - adding classes would be my actual suggestion: - but this works for this example. Click a div and all divs are hidden then the clicked one is shown. I also added a reset button to allow all divs to reappear.
$('div').click(function(){
$('div').hide();
$(this).show();
});
$('#reset').click(function(){
$('div').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
<hr/>
<button type="button" id="reset">Reset</button>
$(document).ready(function(){
$("div").on("click",function(){
$("div").not(this).toggle("slow");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>

Detach and append divs/html jquery

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"

Javascript click specific to ID

I have a div setup like so:
<div class="content">
<button class="show-comments" id="content1"></button>
</div>
<div class="comments-wrapper" id="comment1"></div>
<div class="content">
<button class="show-comments" id="content2"></button>
</div>
<div class="comments-wrapper" id="comment2"></div>
I have the following code:
$('.show-comments').click(function(e){
e.preventDefault();
$('.comments-wrapper').slideToggle('slow');
});
As you would assume, the code works but on a class basis. I'd like for it to open up only the .comments-wrapper of its associated id (i.e. open slideToggle comments2 if content 2 button is clicked and so on and so on).
How would I do this?
$('.show-comments').click(function(e){
e.preventDefault();
$(this).closest(".content").next('.comments-wrapper').slideToggle('slow');
});
Note that this is dependent on the .content element being immediately followed by the .comments-wrapper.
If you have access to modify the html itself, I would suggest adding a wrapper element and then doing the following to avoid the reliance on the exact order of elements:
<div class="wrapper">
<div class="content">
<button class="show-comments" id="content1"></button>
</div>
<div class="comments-wrapper" id="comment1"></div>
</div>
<div class="wrapper">
<div class="content">
<button class="show-comments" id="content2"></button>
</div>
<div class="comments-wrapper" id="comment2"></div>
</div>
$(this).closest(".wrapper").find('.comments-wrapper').slideToggle('slow');
This way, if you add an element between the .content and the .comments-wrapper it does not break the code.
You can do this:
$(this).parent("div").next('.comments-wrapper').slideToggle('slow');
This will find the related div of class .comments-wrapper and slide toggle.
And a fiddle: http://jsfiddle.net/xCJQB/
$('.show-comments').click(function (e) {
e.preventDefault();
var num = this.id.match(/\d+$/)[0];
$("#comment" + num).slideToggle('slow');
});
Demo ---> http://jsfiddle.net/7pkyk/1/
Use this context
$(this).closest('.comments').next('.comments-wrapper').slideToggle('slow');
If it is not the immediate element then you might try this as well
$(this).closest('.comments')
.nextAll('.comments-wrapper').first().slideToggle('slow');
you can add a common class to associate a button with a div.
html:
<div class="content">
<button class="show-comments group1" id="content1"></button>
</div>
<div class="comments-wrapper group1" id="comment1">1</div>
<div class="content">
<button class="show-comments group2" id="content2"></button>
</div>
<div class="comments-wrapper group2" id="comment2">2</div>
javascript:
$('.show-comments').click(function(e){
var associate = $(this).attr('class').match(/group\d+/).pop();
var selector = '.comments-wrapper.' + associate;
e.preventDefault();
$(selector).slideToggle('slow');
});
http://jsfiddle.net/uMNfJ/

Categories

Resources