MajorAlanDutch
MajorAlanDutch

Reputation: 23

Replace img attribute

I have the following img tag that is part of a larger HTML page. This is the first image tag in the document. I would like to change the first image (white.png) with the data-original attribute.

<img width="676" height="450"
     src="http://somewebsite/white.png"
     data-original="http://somewebsite/shutterstock_197488871-676x450.jpg"
     class="lazy attachment-post-thumbnail wp-post-image" alt="(Shutterstock*)"
/>

Here is the HTML

  <div style="font-size: 12pt; color: #ccc; margin-top: 5px; margin-bottom: 5px;"><span id="author">Natural News</span> | <span>Sat, 16 Aug 2014 13:06:21 PM</span>
</div>
<img width="676" height="450" src="http://somewebsiteimages/white.png" data-original="http://somewebsite/shutterstock_197488871-676x450.jpg" class="lazy attachment-post-thumbnail wp-post-image" alt="(Shutterstock*)" />
<noscript>
    <img width="676" height="450" src="http://somewebsite/shutterstock_197488871-676x450.jpg" class="attachment-post-thumbnail wp-post-image" alt="(Shutterstock*)" />
</noscript>

Upvotes: 0

Views: 130

Answers (3)

Charmless
Charmless

Reputation: 61

The implementation I chose was this

$(document).ready(function () {
    $('img')
    .first()
    .attr('src', $('img').first().data('original'));
});

I added a document ready function and create an anonymous function in that to do the work. First I selected all of the 'img' elements and then using the 'first()' method we limit our method to just the first img element in the document. Then we change the 'src' attribute of the image to the value of the 'original' location on the same 'img' element.

If you could refine the selector to use a class of the image like this you may also have better results

$('img.wp-post-image')

You could also change the jQuery selector to

$('img.wp-post-image:first')

and then you could remove the .first() function call. Which would leave you with this in the .ready function:

$('img.wp-post-image:first').attr('src', $('img.wp-post-image:first').data('original'));

references: jQuery :first selector jQuery .data() method

Upvotes: 0

Patrick Desjardins
Patrick Desjardins

Reputation: 140803

You can do :

var workingImage = $("img").first();
workingImage.attr("src",workingImage.attr("data-original"));

This search for the first image. Then, it changes the source by the attribute.

Upvotes: 0

Oriol
Oriol

Reputation: 288120

To get the image, you can use one of these:

var img = document.images[0];
var img = document.getElementsByTagName('img')[0];

And to change it, one of

img.src = img.getAttribute('data-original'); // old way
img.src = img.dataset.original;              // new way

Upvotes: 1

Related Questions