Search code examples
jquerybackground-image

Change part of url of background-image using jquery


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');

Solution

  • 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>