each function index and element - javascript

my question is a simple one how do you use element with index in each function
$('div').each(function(index, element) {
is element equal to $(this)
});

The element there will always be the same as this.
jsFiddle.
Except wrapping it in $() will make it a jQuery object, and won't be equal to the other one, even if you wrap the other with a jQuery object.
There should never be a reason why you need to compare this to element in that context.

$('div').each(function(index, element) {
//element != $(this)
//element == this
});
$(this) is this wrapped by a jquery object. So while this won't equal $(this), you can still manipulate it to your heart's content
Here's something to look at : http://jsfiddle.net/jomanlk/ZqXPn/

Related

Wrap each element and then prepend a new div to the wrapper?

I'm trying to use jQuery (3.1.1) to wrap elements of a given class and then prepend a new div as the first element inside the wrapper. I've tried a number of things and this is as close as I can get.
testWrap = function() {
var testWrapImpl = function(index, value) {
var div = $("<div></div>");
$(value).wrap(div);
$(div).prepend("<div class='child-div'>some text</div>");
alert("done");
};
$(".myClass").each(testWrapImpl);
This code successfully wraps each element with the outer div but doesn't seem to do anything with the "some text" div.
The alert does show up for each of the elements in the page and the page seems to load with out error.
What am I doing wrong?
You can .prepend() before using .wrap() to achieve what you're after.
Also, once you've defined div variable as a jQuery object, you should reference div variable rather than $(div).
var testWrapImpl = function(index, value) {
$(value).wrap( '<div></div>' ).parent().prepend("<div class='child-div'>some text</div>");
alert("done");
};
$(".myClass").each(testWrapImpl);
https://jsfiddle.net/2966pxqz/4/
The .wrap() method wraps a copy of the wrapper around each target element. Thus once you've called .wrap(), your div thing is a perfectly OK element but it's not the actual wrapper.
What you could do is add a class to the wrapper, do the wrapping, then find the wrappers and add the extra element:
$(".myClass")
.wrap("<div class='wrapper'></div>")
.closest(".wrapper")
.prepend("<div class='child-div'>some text</div>");
There's no real need to do your own .each() iteration; the jQuery routines will do that implicitly. If you need to make decisions about the wrapper for each element in "myClass", you can pass a function to .wrap(). The function will be called for each individual element with a single argument containing the index into the list, and with this bound to the element for that iteration. Your code in the function can inspect the element or do whatever, and the return value from the function will be used as the wrapper. So for example to give a numbered class to each wrapper:
$(".myClass")
.wrap(function(index) {
return "<div class='wrapper wrapper-" + index + "'></div>";
})
.closest(".wrapper")
.prepend("<div class='child-div'>some text</div>");

Event delegation issue with JQUERY

I am new in Jquery and I am trying to understand how event delegation work.
I am trying this:
$("#32298").on( 'click',function() { // event delegation
alert("df");
var imgs = document.getElementById("32298")[0].src;
alert(imgs);
});
When I click on the image with this Id I get the first alert but it doesn't work the second alert.
What am I doing wrong here?
Thank you.
If you want to perform event delegation then the second argument of the event handler function needs to be a selector to match the element that matches the one you want to be clicked.
$(document.body).on('click', "#32290", function(event) {
The problem with your code has nothing to do with event delegation. getElementById returns a single element (an id must be unique in the document), not a HTML Collection. (Compare with getElementsByTagName and getElementsByClassName which use the plural Elements.) It won't have a 0 property.
var imgs = document.getElementById("32298").src;
Since you're using jQuery, you can simply use the $(this) constructor, rather than document.getElementById():
$("#32298").on( 'click',function() {
alert("df");
var imgs = $(this).attr('src');
alert(imgs);
});
For what it's worth, this isn't event delegation by the way, it's just an event bound to an element.
If you must use vanilla JS to fetch the src attribute, you don't need to pass an index to the returned value of getElementById(), since this function returns a DOMObject, not an array. Update as follows:
$("#32298").on( 'click',function() {
alert("df");
var imgs = document.getElementById("32298").src;
alert(imgs);
});
It's also worth noting that IDs should be unique, so #32298 should reference a single element in the DOM. I don't know whether it's a typo, but it appears that you may have multiple elements with the same ID (since you use the variable name imgs - i.e. plural).
you can try this
$("#32298").click( function() {
alert("df");
var imgs = $(this).attr('src');
alert(imgs);
});

How do I use the child element of 'this' as a selector in jQuery?

I have a function that calls when the user mouseover a certain div. The function shows a different div, but the issue is that it shows all of the divs with that class.
Here's the JS:
$('.edit-image').mouseover(
function(e){
$('.edit-image-link').show();
});
What I want it to do is only show the .edit-image-link div if it's a child of the element that the user has their mouse over.
You can use .find() to fetch only the descendant elements of an element based on a selector.
$('.edit-image').mouseover(function (e) {
$(this).find('.edit-image-link').show();
});
or you can pass a context to jQuery for searching a selector
$('.edit-image').mouseover(function (e) {
$('.edit-image-link', this).show();
});
Note: Inside a jQuery callback method like event handlers, this will refer the to current dom element
I personally prefer the first method
Use
$('.edit-image').mouseover(function () {
$(this).find('.edit-image-link').show();
});
References
this keyword
.find()
Get the descendants of each element in the current set of matched
elements, filtered by a selector, jQuery object, or element.

Jquery toggle just the p tags under the div clicked

Quick, simple question.
I have this function working at the moment ;
$("#menuopties").click(function(){
$("p").toggle();
});
However this toggles every p tag.
I just want to toggle the p tags which are under the div #menuopties (which has been clicked)
Thanks.
Your current selector "p" will get all the elements of type p instead of getting the p within the current object. Use find() to get the descendant of current element. you will get the source of event object using $(this)
$("#menuopties").click(function(){
$(this).find("p").toggle();
});
You can use pass current object in context of the selector using jQuery( selector [, context ] )
$("#menuopties").click(function(){
$("p", this).toggle();
});
Try like this
$("#menuopties").click(function(){
$(this).find("p").toggle();
});
How about:
$("p", this).toggle();
try:
$("#menuopties").click(function(){
$(this).find("p").toggle();
});
hope that helped.
Change $('p').toggle(); to $(this).children('p').toggle();
$(this) refers to the current jQuery object (in this case wrapping the #menuopties DOM element), so running .children() allows you to filter its descendant elements by whatever selector you want (in this case p).
edit: as buzzsawddog pointed out, it's important to note .children() only returns the child elements a single level below in the DOM, so if your p tags are not immediate children of #menuopties you should use .find() instead.

changing the value of a child input

I am having troubles in changing the value of a hidden <input> after dropping a sortable element
Here's my JSFiddle
I Am trying to change the value of the hidden <input> that is inside the block <div> when i drop the from the container
i have tried this but with no luck
$('.block1').on("sortreceive", function (event, ui) {
var $list = $(this);
$(this).children().first("input").val = 'Something';
if ($list.children().length > 2) {
$(ui.sender).sortable('cancel');
}
});
jQuery val is a method. So try this
$(this).children().first("input").val("Something");
Assuming the $(this).children().first("input") expression returns a valid object for your DOM
Try
//use .first() only if there are multiple input elements under `this` and you want to set the value to first item
$(this).find("input").first().val('Something');
You can use a combination of .find() and :hidden
$(this).find('input:hidden').val('Something');
Please note that .val = 'Something' is not correct, you should use .val('Something');
Demo here

Categories