How to access js object properties via html element? - javascript

I have an array of objects fetched using jQuery.getJSON(). I want every one of my objects to be represented by HTML div element, so when you click the element you have access to all the properties of corresponding object. What is the best way to do it?
I wanted to do it like this:
$('.mydiv').click(function() {
var id = $(this).attr('id');
for (i=0; i<myObjectsArray.length; i++){
for (x in myObjectsArray[i]){
//..and here I got confused...
}
}
});
Is this approach any good or is there a better way to do it.
Thanks.

You can store data in the data property of your jQuery object
docs here

Related

Retrieve a jQuery element from an array

I am storing jQuery elements in an array, and I need to retrieve them.
I am now doing it like
var arr = [];
arr.push( $(someElement) );
Then I try to retrieve it by doing:
arr.indexOf($(someElement));
But it doesn't work as all jQuery elements look the same e.fn.e.init[1]
I'd rather not name (key) each of them because I have a lot of elements and if I could reference them similarly to how I'm trying to, it would be better for me.
How would you do it?
Why are you storing your jQuery objects in an array ? You can't save jQuery objects to preserve their states as JQuery objects are simply wrappers to the DOM elements chosen by your selector. If the DOM changes, then those changes will be reflected by the jQuery object. If you want to preserve the old values, you should store the properties you want to keep rather than the entire jQuery object. Alternatively, you could also store your jQuery string inside an array:
var arr = [];
arr.push(someElement);
When needed you can then query if your element is still contained in the array
if (arr.indexOf(someElement)){
$(someElement).dostuff......
}

serialize HTML tags/objects in javascript

I know there are a lot of questions on serializing objects in Javascript, but I'm trying to serialize a string to JSON objects after using the method .getData() from one of the APIs for later use. It returns a string, but I can't get any attributes.
Here is an example of what I did. I need to serialize this to a JSON object, but it just returns me this type of object. Is there a way that I can get the source of this audio element after serializing it with JSON.stringtify() ?
http://imgur.com/K4RhCht
You can use JSON.parse(theSerializedElement), set it as the innerHTML of an HTML element that you can dynamically create and then use DOM methods to get the attribute.
If I am understanding you correctly you want to serialize DOM element's attributes or some of them, or may be data attached to it. You will need to iterate through them on your own.
So you have some HTML as a string, and you want to get the value of an attribute in the audio tag?
EDIT: Assuming your string is in the data variable.
If you're using jQuery:
var source = jQuery(data).attr('src');
Without jQuery, it's still fairly straightforward.
var container = document.createElement('div');
container.innerHTML = data;
var source = container.querySelector('audio').getAttribute('src');

jQuery Id Selection and Dynamic Arrays

I have some code I'm struggling with. The good news is the code working as intended for a single instance; after some thought I've decided to feature multiple of these image selectors on a page. This works but the ugly approach of duplicating the code doesn't scale well (e.g. what if you want 50 of these on there?) The snag I've hit is how I can refer to a specific array. Is an array even an ideal solution for this?
The Objective
I have a series of images that a user may select from, up to X amount. The selected image ids are stored in an array and the image is added to a "selected images pool". This occurs by using an onClick for the slider, I obtain the Id from the element attributes. This is where I'm getting stuck.
var dataArray = $(this).closest("[id^=carousel]").data('array');
var slideCounter = $(this).closest("[id^=carousel]").data('counter');
slideCounter = dataArray.length;
The slideCounter returns the length of the string, not the array elements. How can I tell this code to refer to a particular array? See the fiddle for a better idea of the markup and code: jsFiddle
I have no doubt that there is a better approach. I'm relatively new to front end work, I'd appreciate any insights, I've burnt some brain cells on this, thanks!
From looking at your HTML, it looks like when you do this:
var dataArray = $(this).closest("[id^=carousel]").data('array');
what you're trying to do is to read the name of an array with .data() and then somehow turn that name (which is a string) into the array that's in your variable. My guess is that there's probably a better way to structure your code rather than putting javascript variable names in your HTML. I'd probably put a key name in the HTML and then store the arrays in an object where you can access them by that key name at any time.
Without trying to refactor your code, here's an idea for what you were trying to accomplish:
If selectedSlidesIdArray1 is a global variable, then you can do this:
var dataArray = window[$(this).closest("[id^=carousel]").data('array')];
Using the [stringVariable] notation on an object, lets you access a property by a literal string or a variable that contains a string. Since all global variables are also properties on the window object, you can do it this way for global variables.
If selectedSlidesIdArray1 is not a global variable, then you should probably put it in an object and then you can do this:
var dataArray = yourObj[$(this).closest("[id^=carousel]").data('array')];
Instead of trying to translate an arbitrary string into a JavaScript variable of the same name, why not just use another array? You can have nested arrays, which is to say an array of arrays.
Thus, instead of selectedSlidesIdArray1, selectedSlidesIdArray2, etc., you would have one selectedSlidesIdArray with sub-arrays, which you could then pull the index for using a data attribute.

How to tell the containing object in javascript?

I have JSON data and I was wondering if there was a way to determine the parent object of a nested object. For example, take this structure:
Vehicles[]
ForSaleCars[]
Car{}
Make
Model
Year
SoldCars[]
Car{}
Make
Model
Year
Assume that this is in var json = ; and has been filled with some data. It is easy to access the second car in the ForSaleCars array like this:
var secondCar = json.Vehicles.ForSaleCars[1];
At this point, solely from the secondCar variable, is it possible to tell it came from ForSaleCars and not SoldCars?
The reason I ask is that I am traversing a json object graph recursively and it would be nice to see which parent the object had without tracking.
At this point, solely from the secondCar variable, is it possible to tell it came from ForSaleCars and not SoldCars?
No. JavaScript doesn't automatically track where a reference was copied from.
It is not possible. You can maintain hash instead.
No, you are copying from the parent, and JavaScript won't track what the parent reference used to be. If you want to be able to track it, you will need to add a reference:
var secondCar = json.Vehicles.ForSaleCars[1];
secondCar.parent = json.Vehicles;

Call show on array of jQuery objects

I have a little problem concerning performance of jQuery.show.
This problem occurs in IE8 (probably also versions below, but IE8 is of my interest).
I have an array of jQuery objects, lets call it elements.
I want to show them, so i did:
for (var i = elements.length - 1; i >= 0; i--) {
elements[i].show();
}
The bottleneck seems to be the call to show. The array is already generated, so that takes no time. looping through an array should not be a problem either.
I thought of reducing this to one call to show by creating a new jQuery element containing all my elements. but I was not sure how to do this. I tried by jQuery.add.
var $elements = elements[0];
for (var i = elements.length - 1; i >= 1; i--) {
$elements = $elements.add(elements[i]);
}
$elements.show();
Now, this time it seems to be a problem with jQuery.add. Probably because it always creates a new object.
So, I thought of three different approaches that could solve my problem. Maybe you can help me with one of them:
Is there a jQuery method like add that does not return a new object, but instead adds it to the current jQuery element?
Is there an easy and fast way to create a jQuery element by an array of jQuery elements?
Is there a way to show all jQuery objects in an array in a faster way?
Answering just one of the question would probably help me out here. My problem is, that jquery always expects an array of DOM elements and not an array of jQuery elements in its methods.
Thanks a lot in advance!
-- EDIT about the contents of elements
I have a jstree that dynamically creates nodes (that is, li elements). These elements have an attribute data-id to identify them.
Now, I could always query for something like $('li[data-id=xxx]'), but this would be very slow. So instead, when li elements are created, i cache them into a dictionary like object (key is the data-id, value is the node). Out of this object, i generate my array elements. This happens very fast.
The array can have a size of up to 4000 nodes. Every jQuery Element in the array only contains one DOM-Element (li).
Edit
After reading your update, and the comments, this Very small one-liner is most likely going to be the answer:
elements.each($.fn.show);
Using the jQ each method to apply (well, internally: call is used) the show method to all elements.
The easiest, and fastest way to create a jQuery object from an array of jQuery objects would be this:
var objFromArr = $(jQarr);
I've just tested this in the console:
objFromArr = jQuery([jQuery('#wmd-input'),jQuery('#wmd-button-bar')]);
objFromArr.each(function()
{
console.log(this);//logs a jQ object
console.log(this[0]);//logs the DOMElement
});
But having said that: you say elements is an array of jQ objects, but if it's the return value of a selector ($('.someClass')) then really, it isn't: in that case, your loop is "broken":
elements = $('.someClass');
for (var i=0;i<elements.length;i++)
{
console.log(elements[i]);//logs a DOMElement, not a jQuery object
}
//It's the same as doing:
console.log(elements[0]);
//or even:
console.log($('.someClass').get(0));
But in the end, if you have an array of jQuery objects, and you want to invoke the show method on each and every one of them, I suspect this is the best take:
elements.each($.fn.show);//use the show method as callback

Categories

Resources