I have a layout similar to this:
<div id="..."><img src="..."></div>
and would like to use a jQuery selector to select the child img inside the div on click.
To get the div, I've got this selector:
$(this)
How can I get the child img using a selector?
The jQuery constructor accepts a 2nd parameter called context which can be used to override the context of the selection.
jQuery("img", this);
Which is the same as using .find() like this:
jQuery(this).find("img");
If the imgs you desire are only direct descendants of the clicked element, you can also use .children():
jQuery(this).children("img");
You could also use
$(this).find('img');
which would return all imgs that are descendants of the div
If you need to get the first img that's down exactly one level, you can do
$(this).children("img:first")
If your DIV tag is immediately followed by the IMG tag, you can also use:
$(this).next();
The direct children is
$('> .child-class', this)
You can find all img element of parent div like below
$(this).find('img') or $(this).children('img')
If you want a specific img element you can write like this
$(this).children('img:nth(n)')
// where n is the child place in parent list start from 0 onwards
Your div contains only one img element. So for this below is right
$(this).find("img").attr("alt")
OR
$(this).children("img").attr("alt")
But if your div contain more img element like below
<div class="mydiv">
<img src="test.png" alt="3">
<img src="test.png" alt="4">
</div>
then you can't use upper code to find alt value of second img element. So you can try this:
$(this).find("img:last-child").attr("alt")
OR
$(this).children("img:last-child").attr("alt")
This example shows a general idea that how you can find actual objects within the parent object.
You can use classes to differentiate your child's object. That is easy and fun. i.e.
<div class="mydiv">
<img class='first' src="test.png" alt="3">
<img class='second' src="test.png" alt="4">
</div>
You can do this as below :
$(this).find(".first").attr("alt")
and more specific as:
$(this).find("img.first").attr("alt")
You can use find or children as above code. For more visit Children http://api.jquery.com/children/ and Find http://api.jquery.com/find/.
See example http://jsfiddle.net/lalitjs/Nx8a6/
Ways to refer to a child in jQuery. I summarized it in the following jQuery:
$(this).find("img"); // any img tag child or grandchild etc...
$(this).children("img"); //any img tag child that is direct descendant
$(this).find("img:first") //any img tag first child or first grandchild etc...
$(this).children("img:first") //the first img tag child that is direct descendant
$(this).children("img:nth-child(1)") //the img is first direct descendant child
$(this).next(); //the img is first direct descendant child
Without knowing the ID of the DIV I think you could select the IMG like this:
$("#"+$(this).attr("id")+" img:first")
Try this code:
$(this).children()[0]
You can use either of the following methods:
1 find():
$(this).find('img');
2 children():
$(this).children('img');
jQuery's each is one option:
<div id="test">
<img src="testing.png"/>
<img src="testing1.png"/>
</div>
$('#test img').each(function(){
console.log($(this).attr('src'));
});
You can use Child Selecor to reference the child elements available within the parent.
$(' > img', this).attr("src");
And the below is if you don't have reference to $(this) and you want to reference img available within a div from other function.
$('#divid > img').attr("src");
Also this should work:
$("#id img")
Here's a functional code, you can run it (it's a simple demonstration).
When you click the DIV you get the image from some different methods, in this situation "this" is the DIV.
$(document).ready(function() {
// When you click the DIV, you take it with "this"
$('#my_div').click(function() {
console.info('Initializing the tests..');
console.log('Method #1: '+$(this).children('img'));
console.log('Method #2: '+$(this).find('img'));
// Here, i'm selecting the first ocorrence of <IMG>
console.log('Method #3: '+$(this).find('img:eq(0)'));
});
});
.the_div{
background-color: yellow;
width: 100%;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my_div" class="the_div">
<img src="...">
</div>
Hope it helps!
You may have 0 to many <img> tags inside of your <div>.
To find an element, use a .find().
To keep your code safe, use a .each().
Using .find() and .each() together prevents null reference errors in the case of 0 <img> elements while also allowing for handling of multiple <img> elements.
// Set the click handler on your div
$("body").off("click", "#mydiv").on("click", "#mydiv", function() {
// Find the image using.find() and .each()
$(this).find("img").each(function() {
var img = this; // "this" is, now, scoped to the image element
// Do something with the image
$(this).animate({
width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + "px"
}, 500);
});
});
#mydiv {
text-align: center;
vertical-align: middle;
background-color: #000000;
cursor: pointer;
padding: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="mydiv">
<img src="" width="100" height="100"/>
</div>
$(document).ready(function() {
// When you click the DIV, you take it with "this"
$('#my_div').click(function() {
console.info('Initializing the tests..');
console.log('Method #1: '+$(this).children('img'));
console.log('Method #2: '+$(this).find('img'));
// Here, i'm selecting the first ocorrence of <IMG>
console.log('Method #3: '+$(this).find('img:eq(0)'));
});
});
.the_div{
background-color: yellow;
width: 100%;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my_div" class="the_div">
<img src="...">
</div>
If your img is exactly first element inside div then try
$(this.firstChild);
$( "#box" ).click( function() {
let img = $(this.firstChild);
console.log({img});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box"><img src="https://picsum.photos/seed/picsum/300/150"></div>
With native javascript you can use
if you've more than one image tag then use
this.querySelectorAll("img")
if only one image tag then us
this.querySelector("img")
You could use
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$(this).find('img');
</script>
Related
I have a couple of functions, the first replaces the contents of a div the second restores the original div. The problem is because I'm using the replaceWith method, the second div no longer exists if I try to call it a second time. Is there a better way to do this? I've experimented creating a variable that stores the contents of the second div so I can resuse it, but could not get it to work.
The code that I have is:
$(document).ready(function() {
$('#trigger_adults').click(function() {
var mainClone = $("#main-content").clone();
$('#main-content').fadeOut('fast', function() {
$('#main-content').replaceWith($('#adults'));
$('#slider-sec').slideUp('slow');
$('#adults').fadeIn('fast');
$(window).scrollTop(0);
});
$('#return').click(function() {
$("#adults").replaceWith(mainClone.clone());
$('#adults').fadeOut('fast');
$('#slider-sec').slideDown('slow');
});
});
});
Thanks in advance!
You could have both contents in the same div and toggle the visibility of their parent divs. Use javascript just to toggle the wrapper's class.
$('#toggle').click(function() {
$('#wrapper').toggleClass('init-state new-state');
});
#wrapper {
border:1px solid #d8d8d8;
}
.init-state #new,
.new-state #init { display:none; }
.inner {
padding:25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="wrapper" class="init-state">
<div id="init" class="inner">Initial Content</div>
<div id="new" class="inner">New Content</div>
<button id="toggle" type="button">Toggle</button>
</div>
From the docs
The .fadeOut() method animates the opacity of the matched elements. Once the opacity reaches 0, the display style property is set to none, so the element no longer affects the layout of the page
you either need to manually set the display style property back to its original value, or call jQuery's .fadeIn() function which will do the opposite of .fadeOut()
Demo is here.
When I click on any image, I want to get the path of that image. The problem here is that only the path of image 1 is being given every time.
Also, with that new src, i want to add that src in the image having id= cropimage
$(".img").click(function() {
var newsrc = $(".img").attr("src");
alert(newsrc);
});
Use $(this) inside click event handler to get the element that is clicked. $(this) inside event handlers is the element on which the event has occurred.
If you use $('.img'), it'll select all the elements having class img and when use attr on it, it'll return the attribute value of the first matched selector.
Demo
$(".img").click(function() {
var newsrc = $(this).attr("src");
$('#cropimage').attr('src', newsrc);
// Even Shorter Form
// $('#cropimage').attr('src', $(this).attr('src'));
});
#cropimage {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<img class="img" src="http://www.w3schools.com/images/w3schools.png" />
<br/>
<img class="img" src="https://www.google.co.in/images/icons/hpcg/ribbon-black_68.png" />
<div id="img-container">
<img src="" id="cropimage" />
</div>
Please check this link Js Fiddle it will help you.
$( ".img" ).click(function() {
var newsrc=$(this).attr("src");
//alert(newsrc);
$( "#cropimage" ).attr("src",newsrc);
});
I have this HTML:
<li class="chatbox-item">
<div class="item">
<div class="item-header">
X
</div>
</div>
</li>
When a.close-chatbox is clicked, the .item element has to be hidden. However, I just can't seem to go up two levels to hide the .item element.
I have this JS:
$(".close-chatbox").click(function() {
// not working
$(this).parent().parent().hide();
// not working, hides `.chatbox-item` element, and eq(1) doesn't do anything either
//$(this).parents().eq(2).hide();
});
How can I get the .item element to be hidden when the .close-chatbox element is clicked?
Don't assign your action to a var, just use it:
$(function () {
$(".close-chatbox").click(function () {
$(this).parent().parent().hide();
});
});
JSFiddle: http://jsfiddle.net/ghorg12110/tkocx8ng/
You can either use,
$(this).parent().parent().hide();
or you can use .closest("element"),
$(this).closest(".item")
Use .closest() in jquery
$(this).closest('.item').hide();
Fiddle
Probably a stupid question, but I couldn't find a direct answer, so how can I change ":not('#home div, .nav')" in to something like ":not('this div, .nav')"? That would allow me reuse the same function for different objects.
$( "#home" ).click(function() {
$("#content .plates").children(":not('#home div, .nav')" ).fadeOut(700);
});
and here is the HTML if needed:
<div id="wrapper">
<div id="content">
<div id="home" class="plates">
<div class="nav"></div>
<div id="one"></div>
<div id="two"></div>
</div>
<div id="about" class="plates">
<div class="nav"></div>
<div id="three"></div>
<div id="four"></div>
</div>
</div>
</div>
Thanks for your help!
In the handler, this will be the clicked element, so you could just use this:
$( "#home" ).click(function() {
$("#wrapper #content .plates").children(":not('#"+this.id+" div, .nav')" ).fadeOut(700);
});
The OP is asking for something generic that can be reused on both the "home" and the "about" divs (and maybe on others to be added later?). But, for each one, excluding the "nav" item from the fadeout. So try this:
function myFunc( clickableItem) {
$(".plates:not(" + clickableItem + ")").children( ":not('.nav')" ).fadeOut(700); }
$( "#home" ).click( function(){
myFunc( "#home");
});
$( "#about" ).click( function(){
myFunc("#about");
});
You are using CSS selector :not(), but you can also use jQuery chained function .not(), which subtracts matched elements from another set of matched elements.
The usage is like this:
$(selector1).not(selector2).fadeOut(700);
Where elements in selector2 will get substracted from set matched by selector1.
Let's start from the top. Provided you follow the spec and IDs are unique on your page (as they should be), your click event selector should be just
$("#home").click(function() {...});
Also, the inner selector should be
$("#content .plates").children(...);
There's no need to stack ID selectors in front of other ID selectors since IDs should be unique and selectors are parsed from right to left.
You can use jQuery not to exclude the clicked element.
Code:
$("#wrapper #content #home").click(function () {
$("#wrapper #content .plates").children(':not(.nav)').not($(this)).fadeOut(700);
});
Demo: http://jsfiddle.net/IrvinDominin/dms6u1ww/
$("#wrapper #content #home" ).click(function() {
$("#wrapper #content .plates").children().not($('div', this)).not('.nav').fadeOut(700);
});
I have a trigger element and a responding element.
<div class="more"></div>
<div class="info"></div>
I would like to bind an open/close type event.
$('.more').delegate($('.more'), 'click', function(){
$(this).removeClass('more');
$(this).addClass('less');
$(this).text("less...");
$('.info').addClass("open");
});
$('.less').delegate($('.less'), 'click', function(){
$(this).addClass('more');
$(this).removeClass('less');
$(this).text("more...");
$('.info').removeClass("open");
});
It doesn't work as intended, if the second function is nested in the first then you can open and close only once.
If the script is formatted sensibly as above it will open but not close.
Could anyone help me out?
Bonus if the script could support the .info could be either a sibling or the element immediately following $(.more/.less)'s parent.
I've been toying with .on/.live/.bind but less successfully than above.
Use event delegation ,and binded to document or immediate parent,not same element
$(document).on( 'click',".more", function(){
$(this).removeClass('more');
$(this).addClass('less');
$(this).text("less...");
$('.info').addClass("open");
});
$(document).on('click',".less", function(){
$(this).addClass('more');
$(this).removeClass('less');
$(this).text("more...");
$('.info').removeClass("open");
});
DEMO
NOTE: delegate was outdated with latest version of jquery ,so use on instead,
ISSUE: you are delegated with same element $('.less'),$('.more') use immediate parent or document
Just use JavaScript to toggle a class, and let CSS magic do the rest. Here is a demo: http://jsfiddle.net/pomeh/69sX5/1/
And here is the code:
HTML
<div>
Some visible content
</div>
<div class="content-fold">
<div class="more">More...</div>
<div class="less">Less...</div>
</div>
<div class="info">Some hidden additional content</div>
CSS
/* Additional content and Less button hidden by default */
.content-fold + .info, .content-fold .less {
display: none;
}
/* Additional content and Less button shown when class shown is active */
.content-fold.shown + .info, .content-fold.shown .less {
display: block;
}
/* More button hidden when additional content is shown */
.content-fold.shown .more {
display: none;
}
/*
You can also move the "div.info" into the "div.content-fold",
and use ".content-fold.shown > .info" instead of ".content-fold.shown + .info"
Browser support is quite good for adjacent selector (see http://www.quirksmode.org/css/selectors/#t11 and https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors#Browser_compatibility)
*/
JavaScript
$('.content-fold').on('click', function(){
$(this).toggleClass('shown');
});
Use id to do your task. it's easy.
Html
<div class="more" id="toggle"></div>
<div class="info"></div>
Jquery
$('#toggle').click(function(){
var $this = $(this) //store object
if($this.hasClass('more')) {
$this.removeClass('more').addClass('less').text('Less...')
$this.next('.info').addClass('open');
} else {
$this.removeClass('less').addClass('more').text('More...')
$this.next('.info').removeClass('open');
}
});
js Fiddle: http://jsfiddle.net/5N6TL/53/