New way of jquery object creation - javascript

My code has this line.
var variableName = $("<div class='class-name'></div>");
console.log(variableName); -> Object[div.class-name]
I wanted to know what does this refers to in Jquery and how we can add move values in that object like
Object[div.class-name, div.class-name]
The actual Code is :
var overlapCollector;
$.each(region, function(i, r){
var overlapper = $("<div class='markup-overlapper'></div>").appendTo( markupCanvas );
overlapper.css({
"position": "absolute",
"left": r.x1,
"top": r.y1,
"width": r.x2-r.x1,
"height": r.y2-r.y1
}).toggleClass("exclude", ex);
overlapCollector = overlapper.add(overlapper);
console.log(overlapCollector);
});
Please help
Thanks

You have to use .add() but you also have to remember that this function does not append to the current object, but returns a new object containing what you want.
the appropriate behavior will be ensured by using:
var variableName = $("<div class='class-name'></div>");
variableName = variableName.add($("<div class='another-div'></div>"));
console.log(variableName); -> Object[div.class-name, div.another-div]
EDIT: Since the comment below asked about looping:
var variableName = $("<div class='class-name'></div>");
for(...){
variableName = variableName.add($("<div class='another-div'></div>"));
}
console.log(variableName); -> Object[div.class-name, div.another-div, ..., div.another-div]

You can use .add() to create a new jQuery object with elements added to the set of matched elements. It returns the set of matches as a new jQuery object.
So your code might look like:
var variableName = $("<div class='class-name'></div>");
variableName = variableName.add($("<span class='new-class'></span>"));
console.log(variableName); // -> Object[div.class-name, span.new-class]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Simply do this
$("<div class='class-name'></div><div class='class-name'></div>")
or this
$("<div class='class-name'></div>").add("<div class='class-name'></div>")

Unsure what you mean by "creating move (more?) values in that object".
If you are referring to attributes, you can do:
var x = $('<div/>', {"class":"class-name", "id":"someId"});
If you are wanting to add another object to your current collection, you'll need to use .add() (as mentioned):
var x = $('<div/>');
x.add('div');
here you will end up with 2 divs in your "collection". Also, the jQuery object collection will return in the order that the elements appear in the DOM - not in the order you may have added to the collection....
HTH

Related

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

Jquery changing ID of cloned element children not working

I am trying to clone an element and then change the id of one of its children:
var s = $('.RunWell').clone().wrap('<div>').parent().html();
s.find('#tag' + runNum).attr('id', 'tag'+ (++runNum));
but it is not working, what am I doing wrong ??
how to change the ID of a child of a cloned element ?
you don't have to go to its html..just use the cloned jquery object.
try this
var s = $('.RunWell').clone().wrap('<div>');
s.find('#tag' + runNum).attr('id', 'tag'+ (++runNum));
the line
var s = $('.RunWell').clone().wrap('<div>').parent().html();
assigns variable s with a string value. But you are assuming it to be a jquery object in the next line by performing a .find on it.
It should be
var $s = $('.RunWell').clone().wrap('<div>').parent();
$s.find('#tag' + runNum).attr('id', 'tag'+ (++runNum));
//$s is used to denote it as a jquery object to provide more readability to code.

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);

Associative style arrays in Javascript?

I'm trying to assign an object in the style of an associate array in JS but it's failing, saying 'task.id' is undefined. Why is this?
var response = Object();
$('.task-list').each(function() {
response[this.id][$('#' + this.id).sortable('toArray')];
});
You are referencing the object as a two dimensional array.
You should do it more like this:
var response = {};
$(".task-list").each(function () {
response[this.id] = $(this).sortable('toArray');
}
Also, when you say the error is "task.id is undefined", do you mean "this.id is undefined"? If you are selecting elements based on class, they may not have an explicit id.
<span class="task-list">myTask</span>
You may want to include an id:
<span class="task-list" id="myTask">myTask</span>
You are trying to access a property that you haven't created yet. Although it's not actually clear what you are trying to do from your example. I'm assuming you want to set the value of response[this.id] to $('#' + this.id).sortable('toArray')?
Try this instead:
var response = {};
$('.task-list').each(function() {
response[this.id] = $(this).sortable('toArray');
});
Also changed it to use $(this) instead of $('#' + this.id) as it's cleaner imo.

Jquery: Matching indexes of two arrays, string and object to replace text in object?

I have two arrays, one is full of strings, the other is an array of objects. The indexes on each correspond, and I want to replace the text of each of the objects in my object array with the corresponding text in my string array.
For example, I have an array like this:
var textarr = ["value1", "value2", "value3"]
and a Jquery object array that contains a bunch of span elements:
var spans = $("span.myClass");
var spanarr = $.makeArray(spans);
I'm trying to use $.each() to iterate over each of the spans and use the corresponding index of my text array to assign a text value to the current span.
I've tried a couple different ways, and nothing seems to work. I'm missing some logic here, but why wouldn't this work?:
i = 0;
jQuery.each(spanarr, function() {
$(this).text(textarr[i]);
i++;
});
EDIT:
I think maybe the rest of my function might be causing this not to work. Here's the entire script:
$("span input:radio").click(function() {
if (($(this).is(":checked")) == true) {
var parent = $(this).parent();
var aunts = parent.parent().children();
var parentIndex = aunts.index(parent);
var indexToNthChild = parentIndex + 1;
var otherSpans = $(".DropDownMenu span:nth-child(" + indexToNthChild + ")");
var position = parent.position();
var topValue = position.top;
var smallPrice = otherSpans.children("span.dropDownPrice");
var pricearr = jQuery.makeArray(smallPrice);
var textarr = [];
jQuery.each(pricearr, function() {
textarr[i] = $(this).text();
});
alert(textarr); // Returns all the text values expected in array
var changers = $(".bigPriceChanger");
var changerarr = $.makeArray(changers);
$(".DropDownMenu").css({ "top": "-" + topValue + "px" });
$(".DropDownMenu span").css("background-image", "none");
parent.css({ "background": "#f3f1e7 url(assets/images/branding/DropDownArrow.gif) no-repeat right" });
otherSpans.css({ "background": "#f3f1e7 url(assets/images/branding/DropDownArrow.gif) no-repeat right" });
alert(changearr); // Returns all span objects in array
i = 0;
jQuery.each(changearr, function() {
$(this).text(textarr[i]);
i++;
});
}
});
Try
$("span.myClass").each(function (i) {
$(this).text(textarr[i]);
});
I think you don't need the call to makeArray. Just write:
i = 0;
jQuery.each($("span.myClass"), function() {
$(this).text(textarr[i++]);
});
I hate to end the question with a 'it was all a dream afterall' copout, but it turns out my browser was funked.
I've since checked my script (and the million variations of it that everyone suggested) in IE8 and someone else's firefox, and low and behold, it works.
You might want to try something like this:
var spans = $("span.myClass");
for(i=0;i<spans.length;i++){
spans[i].innerHTML = textarr[i];
}
You can think of a jQuery object like an extended version of an array. You can use length and [i] in reference to the number of DOM elements selected and the DOM element at a certain index respectively.
Your code is fine, although the makeArray call is redundant
There must be an error somewhere else,
here is your code running fine in firefox
http://jsbin.com/oxiwu
to edit go to http://jsbin.com/oxiwu/edit
I think your code is not working because the variable i was defined outside its scope.
Probably there is a better solution, but you could try the following:
function createF() {
var i = 0;
function f() {
$(this).text(textarr[i]);
i++;
}
return f;
}
f = createF();
jQuery.each(spanarr, f);
What's the reason for calling $.makeArray? You can iterate through your spans like this...
$("span.myClass").each(function(i) {
alert(textarr[i]);
$(this).text(textarr[i]);
});

Categories

Resources