Replace the Value of Attribute Data-Image-Src

I am trying to change the value of attribute data-image-src which is used on a div tag like this:-

<div class="bg-image cover-bg"  id="mobile-app"  data-image-src="assets/img/slider-4.jpg" data-overlay="4"></div>

What I need is to change the value of data-image-src from "assets/img/slider-4.jpg" to "assets/img/vs-app.jpg" on click of a button which is made by <a> tag.

1

3 Answers

You can get and set your data attribute like below.

$('a').click(function(e) {
  $('.bg-image').data('image-src', 'assets/img/vs-app.jpg');
  console.log($('.bg-image').data('image-src'));
});
<script src=""></script>
<div class="bg-image cover-bg" id="mobile-app" data-image-src="assets/img/slider-4.jpg" data-overlay="4">1234</div>

<a href='#'>Click to change<a/>

I would recommend using attr() because of compatibility with IE. Details here.

$("#click").on("click", function() {
  $("#mobile-app").attr("data-image-src", "assets/img/vs-app.jpg");
});
<script src=""></script>
<div class="bg-image cover-bg"  id="mobile-app"  data-image-src="assets/img/slider-4.jpg" data-overlay="4"></div>
<a id="click" href="#">Click</a>

You can try this

<a href=' onclick='return change()'>change</a>

<script type='text/javascript'>

function change()
{
    //Change the value of data-image-src here
    return false;
}
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest