views:

83

answers:

2

If I run it. It returns no errors. And in firebug it does in fact select the proper elements in the DOM.

If I break it apart and do something like this :

$('img[hspace]').css('marginLeft', ($('img[hspace]').attr('hspace') / 2) + 'px')

That works.

Here's the monster in its entirety.

$('img[hspace]').each(function(el){
    var pixels = parseInt($(el).attr('hspace'));
    if(isNaN(pixels) || pixels < 1)
        pixels = 0;
    else
        pixels = pixels / 2;
    $(el).css('marginLeft', pixels + 'px')
         .css('marginRight', pixels + 'px')
         .removeAttr('hspace');
});

Update

My HTML :

 `<div class='grid_7'>
        <p><p>
            this is mys</p>
        <p>
            <img align="left" alt="dude its me" border="10" height="168" hspace="30" src="http://s3.amazonaws.com/hq-photo/root/system/photos/6187/resized_orig/photo.jpg" vspace="10" width="130" /></p>
        <p>
            this is as good as it gets</p>

        <p>
            this isasd</p>
        <p>
            sdfasdfasdfasdfasd</p>
        <p>
            asdfasdfasdf</p>
        <p>

            asdfa</p>
        <p>
            sdfasdfasdf</p>
        <p>
            &nbsp;</p>
        <p>
            &nbsp;</p>
        <p>

            &nbsp;</p>
        <p>
            &nbsp;</p>
        <p>
            &nbsp;</p>
        <p>
            <img align="right" alt="it's also me" border="50" height="168" hspace="50" src="http://s3.amazonaws.com/hq-photo/root/system/photos/6187/resized_orig/photo.jpg" vspace="50" width="130" /></p></p>
      </div>`
+6  A: 

The each function passes in the index as the first parameter, not the element. You probably want to do $(this) rather than $(el).

Greg Campbell
Or - `function(idx, el) { }` should do the trick too... http://api.jquery.com/each
gnarf
Interesting. In my example that I'm working with, the `this` didn't work, but the `(idx, el)` did. And by work, I just mean it passed without error. But no actual changes were made to my DOM. Anyone have any idea why? The content that I'm parsing is coming out of a WYSIYWYG so there's a lot of `/n` 's all around. Again if I just run this without a loop, it'll at least target one and move it successfully.
Trip
It might be helpful if you could post some sample HTML, so the code could be tested against an actual DOM.
Greg Campbell
+4  A: 

el references the index of the element in the collection and not the element. Either

  • add a second parameter to the function, this will be the element.
  • use this inside of the function. this references the element
Russ Cam