How to set id to an element in jquery? - javascript

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>

Related

How to change specific element in a class?

I would like to edit a specific attribute from a class in css/JS/JQuery on hover of a different element, but I'm not sure how to do it
eg.
<h1 class="result">Lorium</h1>
<h1 class="result">Ipsum</h1>
<h1 class="result">Dolor</h1>
<img src="example.png" class="images"/>
<img src="example.png" class="images"/>
<img src="example.png" class="images"/>
so that when I hover on one of the <h1> tags, it will change the src of the <img>, but the rest will stay the same. Would I do this in CSS, JS or JQuery? How?
Note: they have to be classes, rather than id's, because I am using PHP to call all these elements and they have to be styled
thanks,
a tired programmer
Firstly you need to detect the hover / mouseenter on the H1 element with the class result.
I am going to assume that all your results have the class result.
$('.result:eq(0)').mouseenter(function(){
console.log("hello world");
});
Next you need to change the img src associated with the result - again I am going to assume all your imgs have the same class.
$('.result:eq(0)').mouseenter(function(){
$('.images:eq(0)').attr('src','https://via.placeholder.com/150x150')
});
I would suggest you to write a function so that you are not having to hardcode the nth value of the class selector.
Further reading: https://api.jquery.com/eq-selector/
If you are not using jQuery - similar logic but you will use document.querySelector('.result')[0] etc.
Further reading: http://mdn.beonex.com/en/DOM/Element.querySelectorAll.html
EDIT -- For nth value where n is the same index number for both result and images
$('.result').mouseenter(function(){
var nValue = $(this).index();
$('.images:eq('+nValue+')').attr('src','https://via.placeholder.com/150x150')
});
First of all, the structure of your HTML does not seem really scalable. I wouldn't count on order of elements. I would instead rewrite the HTML into something as the following:
<div class="result-container">
<h1 class="result">Result title</h1>
<img src="something.png" class="image" />
</div>
And then to handle events using jQuery, you can do something as follows:
function onHoverIn() {
const resultTitle = $(this);
const image = $(this).parent().find('.image')[0];
image.attr('src', 'something-hovered.png');
}
function onHoverOut() {
// same logic
}
$('.result-container .result').hover(onHoverIn, onHoverOut);
Hope that helps!
In jQuery, typically you can change an image like this:
$(".images").attr("src","second.jpg");
But as you can see, because all the images have same class you probably won't achieve what you are looking for. You need something to differentiate images from each other if you are looking to map them to the header tags.
Since you have multiple, you are probably looking at something like:
$('.images').each(function() {
//count the index and flip the image
});

Remove duplicated value that generated by element data

I have a group of images, each of the image have data-type="type,type", so in order to make my life easier I intend to grab the data-type, and make them into an array (wrapped each of them in span) and append them to an "category" element.
$('li.grid-item').each(function () {
// grab a reference to the current li
var $el = $(this);
// get the url from its data-class attribute
var arr = $el.find('img').data('type').split(',');
$.each(arr, function (index, value) {
$el.find('.category').append('<span>' + value + '</span>');
$el.addClass(value);
});
});
<li class="grid-item">
<figure>
<img src="img/sticker/still/sticker_30.png" alt="sticker" title="You know I'm good" data-type="others/" data-price="9 bahts" data-alt="img/sticker/ani/sticker_30.gif" />
</figure>
<a href="#">
<span class="download ala_carte">CONTINUE</span>
</a>
<div class="category"></div>
</li>
It work fine but duplicated 20 of each value, please help. How to remove those duplicated array value? Please help, thanks in advance.
I think it's better to collect all existing types first in on array (and only add new values to it, if there weren't already existing). Afterwards, you could add span elements for each type. And you should only have one "category" container to list all types.
Update
Your function is executed to often (more than 20 times), because you are calling it everytime your $grid.imagesLoaded() makes progress. Call it when you are "done".
Try replacing
$grid.imagesLoaded().progress()
with
$grid.imagesLoaded().done()
to call your function only once after all images are loaded. Additionally you could empty the category container before re-filling it.

JQuery loop duplicate result

Currently I have a list of elements for an isotope page. The basic markup for an element is:
<div class="element conference-box"> <img src="#" class="conference-image" alt="">
<div class="caption">
<div class="confback"></div>
<h3 class="conference-title"></h3>
<h4 class="conference-details"></h4>
</div>
</div>
There around 30 or so elements on the page.
I've been trying to use jQuery to take the image with the class "conference-image" and apply it as a background image to the .confback div, while retaining the original image. I had some success using this code:
$('.element').each(function() {
var getImageSrc = $('.conference-image').attr('src');
$('.confback').css('background-image', 'url(' + getImageSrc + ')');
return true;
});
However, my script takes the image from the very first element and applies that as the background image for every .confback div in every element on my page. Obviously, I would like each individual element to use the image that has been used in that particular element.
Within the .each callback, the this variable will be the .element that's currently being looped over. You can use that to search within just that element for the img and div you want to work with by re-wrapping it with jQuery and using the find method:
$('.element').each(function() {
var getImageSrc = $(this).find('.conference-image').attr('src');
$(this).find('.confback').css('background-image', 'url(' + getImageSrc + ')');
});
Also note, the documentation for .each says:
Use return false to break out of each() loops early.
That doesn't mean you have to use return true to continue the loop, not returning anything is also valid - so I removed it from my example above.
Inside your .each function $(this) will be the elements with class element. You want to use the attributes and css of it's descendants, found using find:
$('.element').each(function() {
var getImageSrc = $(this).find('.conference-image').attr('src');
$(this).find('.confback').css('background-image', 'url(' + getImageSrc + ')');
});

How to pass an array id into jquery selector?

I have an element with an array id id="x[]" that vary depending on the number of elements that I have on a database. It's basically a x button to delete a certain table row in the database.
<div align="center" id="x[]" class="x">
<img src="x 2.png" alt=""></div>
Problem is, I don't know how to pass this id into the jQuery selector. I want to change the form action to delete the row and create an hidden input to get the paramater I need from another field with an array id id="codsinmov[]" with the same index as x[]. What I have so far is:
$(document).ready(function(){
for(var i=0; i<x.length; i++) {
$('#x[i]').click(function(){
var $hiddenInput = $('<input/>',{type:'hidden',id:codsinmovesse, name:codsinmovesse});
$hiddenInput.val($('#codsinmov[i]').val());
$hiddenInput.appendTo('#tabelaeditavel');
$('#form').get(0).setAttribute('action', 'deletemoviment.php');
$('#form').submit();
});
}
});
But it doesn't work.. So, any ideas? Sorry, I'm a beginner at jQuery. Thank you very much!
you can use
$("div[id^='x['").click(function(){
// write code here })
So this will execute on click of those ids of div which start from x.
So as per my understanding You need not to use for loop here rather use 'this' keyword and do what you want.
I hope it will help you.
If you want to add an eventListener to ALL elements you can simply do it like that
var $myButtons = $('.buttons');
That way the whole list of Elements are stored behind the variable $myButtons.
Now you can proceed as following:
$myButtons.on("click", function(event){
console.log(this); // this will print out the clicked element
});
This way every element with the class .buttons is clickable and accessable.
If you want to dynamically select a single element with jquery depending on some value you have to exclude your [i] from the string
for example like that $('element:nth-child('+[i]+')');

Javascript loop through images attributes

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

Categories