minimal
minimal

Reputation: 457

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

Upvotes: 1

Views: 2222

Answers (4)

HMR
HMR

Reputation: 39270

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

Upvotes: 1

codeVerine
codeVerine

Reputation: 762

I think you are looking for this :

var divYouWantToChange = $("#"+array[0]);

Upvotes: 1

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 66971

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

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074305

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.

Upvotes: 4

Related Questions