0

I have a dynamically created background-image for an embedded YouTube video. Now I want to change a part of the background-image url.

This is my HTML code:

 <div class="jet-video__overlay--custom-bg" style="background-image: url(https://i.ytimg.com/vi/B3xqE5F2zHQ/maxresdefault.jpg);">

Now I want to change the "maxresdefault" in the url with "hqdefault" using jquery.

This is what I tried so far:

 $('.jet-video__overlay--custom-bg').attr("style").replace('maxresdefault','hqdefault');
2
  • That's cool, but what you have tried so far? Commented Jun 2, 2021 at 6:52
  • @Shiz this is what I tried: $('.jet-video__overlay--custom-bg').attr("style").replace('maxresdefault','hqdefault'); Commented Jun 2, 2021 at 6:57

1 Answer 1

2

Use .css('background-image') and replace like this

$(document).ready(() => {
 $('.jet-video__overlay--custom-bg')         // element to set the background to it */
 .css('background-image' ,                   // use .css('background-image'
     $('.jet-video__overlay--custom-bg')     // element to get the background from it
     .css('background-image')                // get the background
     .replace('maxresdefault' , 'hqdefault') //replace it
  );
});
.jet-video__overlay--custom-bg{
  width : 300px;
  height : 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="jet-video__overlay--custom-bg" style="background-image: url(https://i.ytimg.com/vi/B3xqE5F2zHQ/maxresdefault.jpg);"></div>

Also as @Rory suggested Easy & Simple you can use , (i , value) => return .replace....

$(document).ready(() => {
 $('.jet-video__overlay--custom-bg')
 .css('background-image', (i, v) => v.replace('maxresdefault', 'hqdefault'));
});
.jet-video__overlay--custom-bg{
  width : 300px;
  height : 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="jet-video__overlay--custom-bg" style="background-image: url(https://i.ytimg.com/vi/B3xqE5F2zHQ/maxresdefault.jpg);"></div>

Sign up to request clarification or add additional context in comments.

6 Comments

Glad it helped .. Have a great day @CliffVandyck :-)
Just FYI this can be made more succinct with $('.el').css('background-image', (i, v) => v.replace('maxresdefault', 'hqdefault'));
@CliffVandyck answer updated with Rory suggestion :)
Thanks @RoryMcCrossan But it will not work without return .... :-)
It will as the arrow function has an implicit return statement.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.