views:

32

answers:

2

Let me try to explain... Lets say I have the following 'a' tags on a page:

<a href="img1.jpg" class="myClass" alt="0,0,600,200"></a>
<a href="img2.jpg" class="myClass" alt="200,0,600,75"></a>
<a href="img3.jpg" class="myClass" alt="275,0,600,200"></a>
<a href="img4.jpg" class="myClass" alt="475,0,600,50"></a>
<a href="img5.jpg" class="myClass" alt="525,0,600,100"></a>
<a href="img6.jpg" class="myClass" alt="625,0,600,200"></a>

and I want to cycle through all 'a' tags with class 'myClass' and read the alt tag and based on its value assign specific 'style' attributes.

I tried the following:

// get value of alt attribute
var tmp = $("a.myClass").attr('alt');
// split value into an array
var partsArray = tmp.split(',');
// assign array values to a dedicated variable
var a = partsArray[0];
var b = partsArray[1];
var c = partsArray[2];
var d = partsArray[3];

// create inline style string
var style;
style = style + "position:absolute;display:block;";
style = style + "border:1px solid red;";
style = style + "width:" + c + "px;";
style = style + "height:" + d + "px;";
style = style + "top:" + a + "px;";
style = style + "left:" + b + "px;";

// add the style attribute and its value
$('a.myClass').attr('style', style);

but it takes the value of the first 'a' tag 'alt' attribute and assigns the style to all 'a' tags. What I am trying to do is read each 'a' tag, get the 'alt' value and assign a style to THAT 'a' tag only THEN read the next 'a' tag ...

Is there a way to accomplish this WITHOUT having to assign a unique ID or class to each 'a' tag?
I am totally new to jQuery and have spent hours trying and googleing this issue and can't figure out how.
Someone PLEASE help.

+3  A: 

You can use the each method like this:

$('a.myClass').each(function(){
  var tmp = $(this).attr('alt');

  // your further code...
});

The each will iterate over all links with class myClass and get each link's alt value stored in tmp variable you can act upon.

Sarfraz
OMG, THANK YOU! I am so embarrassed that I could not figure this out on my own!
Angie
@Angie: Welcome :)
Sarfraz
+2  A: 

You're actually not too far from where you need to be.

// get value of alt attribute
$("a.myClass").each(function() {
  var tmp = $(this);

  // split value into an array
  var partsArray = tmp.attr("alt").split(',');

  // assign array values to a dedicated variable
  var t = partsArray[0];
  var l = partsArray[1];
  var w = partsArray[2];
  var h = partsArray[3];

  tmp.css({
    "position" : "absolute",
    "display" : "block",
    "border" : "1px solid red",
    "width" : w,
    "height" : h,
    "top" : t,
    "left" : l
  });
});
jessegavin
Thank you! So simple... :o)
Angie