Javascript loop through images attributes - javascript

I have a div on my website which contains a number of images. I'm trying to get the onclick attribute of each of the images inside said div.
<div class="hoi">
<img src="" onclick="alert('hoi')"/>
<img src="" onclick="alert('hoi')"/>
</div>
I've tried the following Javascript code:
var count = $(".hoi img").length;
for(var i = 0; i <= count; i++){
alert($('.hoi').find('img').getAttribute('onclick'));
}
But I get the following error Uncaught TypeError: undefined is not a function
Here is a fiddle
http://jsfiddle.net/4Lhn0u87/7/

There is no method called getAttribute() in jQuery object, you have .attr(). getAttribute() is a dom api method.
$('.hoi img').each(function(){
console.log($(this).attr('onclick'))
})
Also to iterate through a set of elements you can use .each().

onclick is a event you can't use it as a data-attribute.use some other.
Here is the working code:
http://jsfiddle.net/silpa/4Lhn0u87/17/
$('.hoi img').each(function(){
$(this).on('click',function(){
alert($(this).attr('data-onclick'));
})
})
I have change onclick to data-onclick and removed alert('hoi') and placed image_1 and image_2 for understanding

Related

How to set id to an element in jquery?

Basically I am creating x amount of image boxes using jquery append() function with all having the same class name, But now I need to set each box id to i. for avoiding confusion this is what I mean:
for(i=0;i<10;i++){
$('.d').append('<img src="" class="UP__" width="120" height="120">');
$('.d img').attr("id",i);
}
The problem with above code i'm facing is that it sets all 10 img boxes id to 10, But I need to set first box id to 1, second to 2 and so on.
My question is how to set each element id to value of i.
Thanks in advance
Just add id to img tag
$('.d').append('<img src="" id="'+i+'" class="UP__" width="120" height="120">');
First declare your variables (whether using var or let) in order to avoid created global variables, and then you can either add the id within the loop:
for(let i=0; i<10; i++){
$('.d').append('<img src="" id="' + i + '" class="UP__" width="120" height="120">');
}
Or do so outside of the loop:
for(let i=0;i<10;i++){
$('.d').append('<img src="" class="UP__" width="120" height="120">');
}
// here we select all the matching <img> elements, and update
// 'id' property using the prop() method, and the anonymous
// function:
$('.d img').prop('id', function (index){
// 'index' is the index of the current element in
// the jQuery collection over which prop() iterates:
return index;
});
The problem with your posted approach was that you were selecting all the matching elements (in each iteration of the loop) and setting the id of all those elements to the same number. This is avoided by both approaches shown above.
Note that using a numeric character as the first character of an id does complicate the CSS selectors used to target those ids as you first need to escape the number character.
With that in mind, to select the element with id="1" you'd need to use:
#\31 {
/* css */
}
You don't need to give an ID. Just use each function of jQuery.
I added the images manually, but you can make it of course dynamic using your own code.
<div class="d">
<img src="http://afterishtar.pl/images/100x100.gif">
<img src="http://afterishtar.pl/images/100x100.gif">
<img src="http://afterishtar.pl/images/100x100.gif">
<img src="http://afterishtar.pl/images/100x100.gif">
<img src="http://afterishtar.pl/images/100x100.gif">
</div>
Then this.
$(document).ready(function() {
$(".d img").each(function( index ) {
console.log(index);
});
});
Its because you are adding the id to all img tags inside the .d div.
PS: Always have the image src tag properly set. An empty src for image tag creates a lot of problems than it solves. if src is not known or set later, use about_blank.
Also, its always a good recommendation to change the dom as minimal times as possible. When possible, append newly created elements once all the manipulations are complete and before attaching them to DOM.
$(function() {
for (i = 0; i < 10; i++) {
var $img = $('<img src="about_blank" class="UP__" width="120" height="120">');
$img.attr("id", i).attr("title", i);
$('.d').append($img);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="d"></div>

Change all links of a particular class on page load

On this site, all the links inside inventory class need to be changed to this link. I can't find the file to edit it and change the link so I am using JavaScript to do it. I have written the following code but it doesn't work.
<script type="text/javascript">
document.getElementByClass("inventory").href="http://www.inspuratesystems.com/mandviwalla-motors/contact/";
</script>
Correct syntax:
document.getElementsByClassName("inventory")
if there's only one such link on webpage try accessing the first element as above method returns array of DOM objects
document.getElementsByClassName("inventory")[0].href
It should be getElementsByClassName not getElementByClass(typo)
It returns an array-like object of all child elements which have all of the given class names.
Try this:
var elems = document.getElementsByClassName("inventory");
for (var i = 0; i < elems.length; i++) {
elems[i].href = "http://www.inspuratesystems.com/mandviwalla-motors/contact/";
}
is it possible to use jquery ?
try following
$(document).ready(function(){
$('.inventory').each(function(){
$(this).attr('href' , 'http://www.inspuratesystems.com/mandviwalla-motors/contact/');
})
})
You can do this with Jquery
$(document).ready(function () {
$("#link").attr("href", "#someOtherPlace");
});
<a id="link" href="#somePlace">LINK</a>
<!--NOTICE THE HREF VALUE-->

Recieving two values from data attribute one being undefined

I am trying to link to divs together by linking the data-attribute name with the id but seem to receive an error
<div class="pod-container grid_3" data-name="#george">
<div class="pod">
<img src="img/example1.png" alt="">
</div>
</div>
<div id="george">Hello World</div>
I'm referencing jQuery 1.8.3 and using the following code to identify the data attribute on the div i click
<script>
$('.pod-container').click(function(){
var identifyId = $(this).data('name');
console.log(identifyId);
//$(identifyId).show();
});
</script>
but when it is logged in the console I get.
#george testdoc.html:123
undefined testdoc.html:123
You've got two elements with class "pod". One of them has a data-name attribute, and one doesn't. Each click will trigger the event handler on both elements.
Just grab the elements that have the data-name. What you're currently doing is targeting just .pods which may or may not have data-name. With the below code, you're just being specific.
$('.pod[data-name]').click(function(){
var identifyId = $(this).data('name');
console.log(identifyId);
//$(identifyId).show();
});
You have 2 elements with the pod class and are getting 2 events fire. The inner div does not have a data-name attribute.

this.appendChild is not a function

I have JS below that i am trying to dispaly a menu item once the image is clicked under the image and once an item is clicked it disappears. i have multiple images that is why i am building this dynamic content menu. i am planning to add bunch of html element inside userMenuContent by
using var userMenuContent ="<div><form>...</<form></div>";
but to begin with my small test fails
function userMenu() {
var userMenudiv = document.createElement("div");
userMenudiv.setAttribute("class", "statusContainer");
var userMenuContent = "<p>test</p>";
$(userMenudiv).append($(userMenuContent));
$(userMenudiv).hide();
this.appendChild(userMenudiv);
$(userMenudiv).slideDown();
}
<img class="icon" src="image.png" onclick="userMenu()"/>
when i click the image i get
TypeError: this.appendChild is not a function.
i am using jquery 1.8.3 and jquery-ui1.8.24
'this' refers to the window object, not the image.
Don't use inline event handlers. Give the DOM element an id and select it that way.
You can't add a div to an image. Instead, you need to specify another target element
Since you're using jQuery, just do it the jQuery way.
$(document).ready(function(){
$('#userMenuImg').click(function(){
$('#target')
.append('<div class="statusContainer"><p>test</p></div>')
.slideDown();
});
});
<img id="userMenuImg" class="icon" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRMKbTxKTOJbJvVTt2SZak49lARNnCU4D7ECfZn1KspIn6SXDHz3A">
<div id="target"></div>
​
​

How to get the value of the method parameter using javascript?

<a onclick="ToggleGridViewRows(this,'/SharedDocuments/1.0 Qualify');">
<img src="../../../../../../../_layouts/images/collapseminus.gif" />
</a>
The above link tag has an onclick event which has the js method "ToggleGridViewRows".
I need to fetch the second parameter "'/SharedDocuments/1.0 Qualify'" value using js.
How can I do this.
var k = document.getElementById('foo').getAttribute('onclick');
k = k.split("\'");
alert(k[1]);
Fiddle here.
This example assumes your <a> element has an ID of 'foo'. If you want to get all 'onclick' content of every <a> element, you can use document.getElementsByTagName('a').

Categories