Can't get div attributes with jquery's attr() - javascript

The following code:
<div id='idiv' name='ndiv'>
<script>
var attrs = $('#idiv').attr({})
var astr = JSON.stringify(attrs)
console.log (astr)
</script>
produces in the console:
{"0":{},"length":1,"context":{"location":{}},"selector":"#idiv"}
Why isn't the result:
{"id":"idiv","name":"ndiv"}
How do I get the latter?

Try this:
<div id='idiv' name='ndiv'>
<script>
var attrMap = $('#idiv')[0].attributes;
var attrs = {};
$.each(attrMap, function(i,e) { attrs[e.nodeName] = e.value; });
console.log(attrs); // Object {id: "idiv", name: "ndiv"}
console.log(JSON.stringify(attrs)) // {"id":"idiv","name":"ndiv"}
</script>
Fiddle: http://jsfiddle.net/xbuhbqux/

If you want to create an object of all the attributes of an element, refer to this SO answer
to produce the object you have shown:
var idiv = $('#idiv');
var attrs = JSON.stringify({
"id": idiv.attr("id"),
"name": idiv.attr("name")
});
console.log(attrs);

jQuery operators are often chainable and usually return arrays of elements, rather than individual elements.
What you are doings is actually returning a list of matching elements, and asking for attributes for all items in that list, which is also returning a list elements. The JSON.stringify reflects that.

Related

Creating JSON - part loop, part plain string

I have the below code, which loops through the DOM looking for elements that have an id starting with "sale-", with an attribute "data-id", capturing the value, then stripping the opening and closing square brackets - pushing it all into a JSON object:
els = $("div[id^='sale-']");
Array.prototype.forEach.call(els, function(el) {
var id = el.attributes[2].value.replace(/\[|\]/gi, "");
var jsonObject = {"id" :+id};
var myJSON = JSON.stringify(jsonObject);
console.log(myJSON+",")
});
This works and the output is:
Now the problem comes when I want to apply some static JSON code before and after the loop.
I would like something like the below:
// static
dataLayer.push({
'ecommerce': {
'impressions': [
// loop portion
{"id":50450},
{"id":49877},
{"id":49848},
{"id":49912},
{"id":49860},
{"id":49825},
{"id":48291},
{"id":49667},
// static
]
}
});
Firstly you can make the array creation much more simple by calling map() on the jQuery object. From there you can simply add the resulting array to an object with the required structure. Try this:
var idArr = $("div[id^='sale-']").map(function() {
var id = this.attributes[2].value.replace(/\[|\]/gi, "");
return { id: +id };
}).get();
dataLayer.push({
ecommerce: {
impressions: idArr
}
});
Also note that this.attributes[2].value can be improved, but you haven't stated which attribute you're expecting that to target.

jQuery - using inArray() to find index of jQuery object

I have a few divs that I'd like to put into an array.
When I try to use jQuery.inArray(), my div (as a jQuery object) isn't found. Why not?
var myArray = [ $("#div1"), $("#div2"), $("#div3") ];
alert(jQuery.inArray($("#div1"),myArray)); // returns -1
$ creates a new jQuery collection object each time, so var a = $("div"), b = $("div") will actually be two different objects that don't equal each other.
Instead you can just use the selectors or some other identifying feature of the element.
var myArray = ["#div1", "#div2", "#div3"];
However it really depends on your use case.
Two objects are never the same, so when you do
var object1 = $('#div1');
var object2 = $('#div1');
even if you have the same element, the objects are not the same
If you use the same object, it works
var div1 = $('#div1');
var div2 = $('#div2');
var div3 = $('#div3');
var myArray = [ div1, div2, div3 ];
jQuery.inArray( div1 , myArray); // returns 0
You can't use .inArray() for object comparison by content.
I like the approach outlined here. It's very clean.
It's probably because each invocation of the jQuery constructor results in a new instance referring to the same DOM node. What would effectively allow you to demonstrate inArray looks something like this:
var $div1 = $('#div1'),
$div2 = $('#div2'),
myArray = [ $div1, $div2 ];
alert(jQuery.inArray($div1,myArray));
You are not storing any references to the jQuery objects, $("#div1") will return a new jQuery object containing your dom element, you are comparing two different jQuery objects containing the same dom element. inArray will work just fine if you are using the same reference in the array as when you do use the inArray method.
var arr = [],
$d1 = $("#d1"),
$d2 = $("#d2"),
$d3 = $("#d3");
arr.push($d1, $d2, $d3);
console.log(jQuery.inArray($d3, arr));
or see http://jsfiddle.net/EQQ96/2/
You're better off creating an array of ids. When it you roll, you can then see if that id is in your array, and then move forward.
var possiblePositions = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
function randomSpin(sides) {
return Math.floor(Math.random() * (sides || 6) ) + 1;
}
var $currentPiece = $('piece.active');
var currentSpot = $currentPiece.attr('spotPosition');
var spin = randomSpin(6) + randomSpin(6);
var nextSpot = currentSpot + spin;
if (possiblePositions.indexOf(nextSpot)) {
$('#div' + nextSpot).append($currentPiece);
}
If you were to use purely jQuery to manipulate the jQuery Collection then you can use the jQuery index() method. However, the index returned is the position of the element in the dom, not the order in which it was added to the collection. If you need to deal with the order of adding then you're better of using selector strings rather than jQuery Collection:
var myArray = $([]).add( "#div4" ).add( "#div3" ).add( "#div1" ).add( '#div2' );
console.log( myArray.index( $('#div3') ) ); //Output: 2
JS FIDDLE DEMO

How to create Dictionary [Key : value] in jQuery

I have a input elements in html with two important attributes: id, and parentElementId.
I want to create a map/dictionary that looks like this: "id : parentElementId".
var parent = $(".people-autocomplete").map( function(){ return $(this).attr('id')+':'+$(this).attr('parent'); }).get() ;
for know I'm putting the values into a string, which I parse later on in the code. I presume there is a more elegant solution than this.
Use an object:
var obj = {};
$(".people-autocomplete").each(function() {
obj[$(this).attr('id')] = $(this).attr('parent');
});
You can then access the parent of a specific id:
var parent = obj.idName;
or through a string:
var idStr = 'idName';
var parent = obj[idStr];
And you can loop through:
for (idStr in obj) {
var parent = obj[idStr];
}
You can use JSON object for this purpose, You are confusing the usage of .map() in Jquery with map of other languages.
You can create a Json object like,
var xObj = {};
xObj.id = 'parentElemtnId';
alert(JSON.stringify(xObj)); // { id : 'parentElementId' }

jQuery getting value from dynamic array

I have an array with divs ids (in my case its all divs ID values od parent div (#area) ):
jQuery.fn.getIdArray = function () {
var ret = [];
$('[id]', this).each(function () {
ret.push(this.id);
});
return ret;
};
var array = $("#area").getIdArray();
I need to get an array field value, something like this:
var lef = $("#array".[0]).css("left");
Taking a wild swing at it (see my comment on the question):
var array = $("#area").getIdArray();
var lef=$("#" + array[0]).css("left");
That assumes that getIdArray returns an array of strings, where each string is an id value for a DOM element, and that you want to get the left value for the first of those elements.
So for instance, if the array comes back as:
["foo", "bar", "charlie"]
then the selector created by "#" + array[0] is #foo, so you end up getting the left value for the foo element.
If you have an actual JS array within your variable array just use bracket notation to access each individual ID.
// I have the # before-hand since I'm assuming you have just the ID name
var lef = $('#' + array[0]) // this will access the 1st one in the array
I think you are looking for this :
var divYouWantToChange = $("#"+array[0]);
I try to formulate this as an answer because getIdArray is not a jquery function and we don't know what it does. If you'd like to apply a custom filter to the $("#area") collection you can do so using filter. This will return a jquery object where you can get the .css("left") from.
If you'd like to save both the id's and the left property you can do so with the following code:
var objects=[];
$("#area").filter(function(){
$this=$(this);//cache the object
objects.push({id:$this.attr("id"),
left:$this.css("left")
};
});
console.log(objects);

Get multiple CSS properties with jQuery

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

Categories

Resources