Brendan Jackson
Brendan Jackson

Reputation: 335

jQuery and the scope of this

I'm missing something with the scope of this function, I have a cms that automatically adds classes to images but not but doesn't change their alignment so text does not wrap on around them properly. I cannot simply use $("img").attr("align","left"); because that would change every image on the page, that said using the context '"img", this' is not working like I thought it would and does absolutely nothing.

function align_image(){
    console.log("func called");
    if($("img").length){
        if($("img").hasClass("alignleft")){
            $("img", this).attr("align","left");
            console.log("aligned left!")
    }

       if($("img").hasClass("alignright")){
           $("img", this).attr("align","right");
           console.log("aligned right!");
       }
   }
}
align_image();

Does anyone out there know how I could change each img to align with its associated class? Bonus points for why it works.

Edit: codepen demo

Upvotes: 0

Views: 93

Answers (3)

pacifier21
pacifier21

Reputation: 813

I think you can iterate through each of the images, and the iterator function refers to the img DOM element with the "this" reference. Something like this:

function align_image(){
    console.log("func called");
    if ($(this).hasClass('alignleft')) {
        $(this).attr("align","left");
    }

    if ($(this).hasClass('alignright')) {
        $(this).attr("align","right");
    }
}

$('img').each(align_image);

As suggested in the comments (and in other answers), you can also use specific jQuery selectors to accomplish the same:

$('img.alignleft').attr("align","left");
$('img.alignright').attr("align","right");

Finally, according to w3schools, the img align attribute is deprecated, and CSS properties should be used instead. Something like this should work:

img.alignleft {
  float: left;
}

img.alignright {
  float: right;
}

I hope this captures all the angles.

Upvotes: 2

sarfaraj khatri
sarfaraj khatri

Reputation: 150

You better use filter method to find your element and add an attr like this:

$("img").filter('.align-right').attr("align","right") ;                           
$("img").filter('.align-left').attr("align","left") ;

See here

Upvotes: 0

Ayatullah Rahmani
Ayatullah Rahmani

Reputation: 932

Try this. I think its helpfull for you

function align_image(){
    console.log("func called");
   if ($('img').hasClass('alignleft')) {
    $(this).attr("align","left");
    }

   if ($('img').hasClass('alignright')) {
    $(this).attr("align","right");
    }
}
align_image();

Upvotes: 0

Related Questions