Remove IMG height and width attributes with jQuery

You’ll sometimes want to remove the height and width attributes from an image tag. You’ll come across this a lot while working with WordPress content, in which case embeded images are given height and width attributes. A simple one liner of jQuery will allow you to remove the height and width from IMG tags:

$(“img”).removeAttr(“height width”);

Of course the line above will remove height and width from ALL images within your document. You’ll want to better specify the image by including it’s parent container or class.

jQuery’s “removeAttr” will come in handy for other things such as iframes, etc..

Resources

 

Post written by Ed Reckers

Founder and lead web development consultant at Red Bridge Internet : San Francisco WordPress Developers and Consultants.

2 Responses to “Remove IMG height and width attributes with jQuery”

  1. Jonathan

    Hi Ed. This seems exactly what I need in a current project but I’m not sure how to use this code. Would you be able to post an example with further directions? (For example, are we putting this code in a js file and enqueing it in functions.php or is there a way to add it directly in functions?) Any specifics much appreciated.

  2. Ed Reckers

    Jonathan,

    You would just put this any a Javascript file that you are enqueing. It’s jquery so it needs to be in the document ready function.

    $(document).ready(function() {
    $(“img”).removeAttr(“height width”);
    });

    You’d also want to make sure you are using a more targeted css selector, ie. (‘.sidebar .responsive-image img’) or something like that.

    This was an example of a fix I had to make once for a very specific purpose, but it does work.

Leave a Reply