Ask Your Question
2

How can you retrieve the source of an image using JQuery and assign it as a data attribute?

asked 2021-07-24 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-03-27 20:00:00 +0000

lalupa gravatar image

You can retrieve the source of an image using the attr() method in jQuery and then assign it to a data attribute using the data() method. Here's an example:

HTML:

<img src="example.jpg" alt="Example">

jQuery:

var imageUrl = $('img').attr('src');
$('img').data('image-src', imageUrl);

In this example, we first retrieve the source of the image using attr('src') and store it in the variable imageUrl. We then use the data() method to assign this value to a data attribute with the key image-src.

You can then retrieve this data attribute later using data('image-src'). For example:

var imageData = $('img').data('image-src');
console.log(imageData); // Outputs "example.jpg"
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-07-24 11:00:00 +0000

Seen: 8 times

Last updated: Mar 27 '23