What is the cleanest way to put the source attribute string of all images within a div into an array?
I was hoping this would work -
var imageSourceArray = $("#leDiv img").attr('src');
alert(imageSourceArray[3]); //not alerting the source, boo hoo.
Do I need to loop through $("#leDiv img") and add each src string to an array individually? Or is there a more elegant way to do this?
You can use jQuery's map function which is described as:
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
For your example:
var mySources = $('#leDiv img').map(function() {
return $(this).attr('src');
}).get();
Edit: Far more elegant solution, there's obviously still some looping involved internally:
var img_sources = $('#leDiv img').map(function(){ return $(this).attr('src') });
You will in fact need to loop over the collection and add sources individually.
var img_sources = [];
$('#leDiv img').each(function(i,e){
img_sources.push($(e).attr('src'))
})
Some background: jQuery.fn.attr() maps to jQuery.access() internally, the key part of which looks like this:
function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// setter functions omitted here …
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
}
Note the elems[0] part – only the first item in the collection is fed to the subsequent callback function (jQuery.attr() in fact) responsible for extracting the information.
var imageSourceArray = [];
$('#leDiv img').each(function(){
var src = $(this).attr("src");
imageSourceArray.push(src);
});
alert(imageSourceArray[3]);
you already have the src in a collection when you fetch the the images. It may be more efficient to not store the src attributes in another array:
$('#leDiv img').each(function(i,e){
var dosomethingwith = $(e).attr('src');
})
or you could do:
var ImageCol = $('#leDiv img');
alert(ImageCol[3].attr('src'));
Related
I know you can SET multiple css properties like so:
$('#element').css({property: value, property: value});
But how do I GET multiple properties with CSS?
Is there any solution at all?
jquery's css method (as of 1.9) says you can pass an array of property strings and it will return an object with key/value pairs.
eg:
$( elem ).css([ 'property1', 'property2', 'property3' ]);
http://api.jquery.com/css/
Easiest way? Drop the jQuery.
var e = document.getElementById('element');
var css = e.currentStyle || getComputedStyle(e);
// now access things like css.color, css.backgroundImage, etc.
You can create your own jQuery function to do this:
//create a jQuery function named `cssGet`
$.fn.cssGet = function (propertyArray) {
//create an output variable and limit this function to finding info for only the first element passed into the function
var output = {},
self = this.eq(0);
//iterate through the properties passed into the function and add them to the output variable
for (var i = 0, len = propertyArray.length; i < len; i++) {
output[propertyArray[i]] = this.css(propertyArray[i]);
}
return output;
};
Here is a demo: http://jsfiddle.net/6qfQx/1/ (check your console log to see the output)
This function requires an array to be passed in containing the CSS properties to look-up. Usage for this would be something like:
var elementProperties = $('#my-element').cssGet(['color', 'paddingTop', 'paddingLeft']);
console.log(elementProperties.color);//this will output the `color` CSS property for the selected element
I'm trying to create an array in Javascript with a size that is equivalent to the number of times a certain class is found in the DOM, and then iterate through it to grab the text from an input field present in that class. I can easily do this like so:
var count = 0;
$('.className').each(function() {
count++;
});
var classes = new Array(count);
count = 0;
$('.className input[type=text]').each(function() {
classes[count++] = $(this).val();
});
This looks like a lot of code for what seems to be a relatively simple task. Is there a more efficient or less lengthy way of doing this?
Thanks
It looks like you want this :
var classes = $('.className input[type=text]').map(function(){
return this.value
}).get();
But it's a guess : it's not clear why you start by counting all elements of the class and then iterate on the inputs.
You can construct an array of elements directly from your selector via the makeArray function, then transform the result using a map.
var classes = $.makeArray($('.className input[type=text]')).map(function() {
return $(this).val();
});
Use jQuery's map function, then get if you need a pure array:
var values = $('.className input[type=text]').map(function() {
return $(this).val();
}).get();
each passes the index, so you don't need to do it yourself:
var classes = [];
$('.className input[type=text]').each(function(index, value) {
classes[index] = $(this).val();
});
Arrays are dynamic and therefore don't need to be initialized. Create a new array, loop through the inputs and push the values to the new array:
var classes = [];
$('.className input[type=text]').each(function(idx, elem) {
classes.push($(elem).val());
});
This return me object Object. how can make an array of src?
$('#mainContainerPortfolio #activateBox').click(function(){
var clickedAlt = $(this).children('img').attr('alt');
var imgs = $('#mainContainerPortfolio #projectImg[alt="'+clickedAlt+'"]');
imgs.src;
var i = [];
i.push(imgs);
console.log(i);
});
In your code, imgs is a jQuery object, not a DOM element. As such, it does not have a .src property.
If you want the .src property of an image in that jQuery object, then you need to do one of the following:
var src = imgs.attr("src");
or, get the first DOM element from the jQuery object:
var src = imgs[0].src
Also, there are several other errors in your code. If you want to accumulate the src value of all elements that are clicked on into an array, you could do something like this:
$('#mainContainerPortfolio #activateBox').click(function(){
var clickedAlt = $(this).children('img').attr('alt');
var imgs = $('#mainContainerPortfolio #projectImg[alt="'+clickedAlt+'"]');
var srcs = imgs.map(function(index, elem) {
return(elem.src);
}).get();
console.log(srcs);
});
I think there is also a problem with your selector because you can only have one element with an id="projectImg" so there should be no reason to be using the attribute [alt="'+clickedAlt+'"] with it.
Similarly, '#mainContainerPortfolio #activateBox' could just be changed to '#activateBox' since there can only be one object with an id of activateBox.
Because imgs is an object. This line:
imgs.src;
does nothing at all. It just returns that. Nothing is done with the returned value. Change that to:
imgs = imgs.attr("src");
and it should work fine
You could use .map to get an array.
i = imgs.map(function() {
return $(this).attr('src');
});
I am looking to create an array of all the images in a string of HTML.
I've tried using the following but it generates errors if the complete URL path is not present in the src.
var found = $(html).find('img');
$("img").each(
function(index) {
theArray.push( $(this).attr("src") );
});
Quick run down of how to achieve this:
Open with jQuery's DOM Ready function ->
$(function(){
Create the variable found which holds a collection of the elements.
var found = $('p > img');
Create an empty Array to hold our results.
var results = new Array();
Iterate through each of the elements that we found
$.each(found, function(index,value){
For each 'value' (the item) that we find, we want to take the src, and push that src into the array.
results.push($(value).attr('src'));
Erroneous closure
});
Alert the total amount of items in the array;
alert('There is a total of '+results.length+' results in the Array.');
Alert just the src of the 3rd item we added to the array.
alert('The src of the 3rd item is: '+results[2]); //3nd item in array, indexes are 0 based
Erroneous closure
});
Hopefully this helps clear things up a bit.
You can do that with simple and plain JavaScript by creating an "instant" html element:
Create a element
Insert the string as innerHTML
Query the node
Example:
var html = "<html><body><img src='/img1.png' /><br /><img src='/img2.png' /></body></html>";
var node = document.createElement("div");
node.innerHTML = html;
for(var i=0; i < node.children.length; i += 1) {
if (node.children[i].tagName === 'IMG') {
alert(node.children[i].src)
};
}
Just try this:
var imgArray = $('img'),
srcArray = [];
console.log(imgArray); // array of imgs
$.each(imgArray, function() {
srcArray.push(this.src));
});
I have an array inside an $.each function. I want to iterate through it to create a new or modified array. But I need to access the $(this) from the outside $.each loop:
// target these data attributes:
$selector = $('[data-my0], [data-my1], [data-my2]');
$.each($selector, function() {
var $this = $(this), // cache selector
keys = ['my0', 'my1', 'my2']; // array of data keys
// I want to use the keys array to make a vals array to this:
// var vals = [$this.data('my0'), $this.data('my1'), $this.data('my2')];
// This doesn't seem to work (can't read from length 0 error):
var vals = $.map( keys, function( key ) { return $this.data(key); });
});
I think it's possible to do this using using $.each or $.map but this is where I'm stuck. I know $(this) not used normally with $.map like it is with $.each. In this case, I'm trying to pass the $this from the outside that represents the selector.
Wait - you're passing "vals" into your "$.map()" cal instead of "keys":
var vals = $.map( keys, function( key ) { return $this.data(key); });
Here is a jsfiddle. The code works just fine, though without seeing your actual HTML it's hard to know exactly what you expect to happen.