Check if phrase is present in DIV style

So I have a DIV that contains a background image. In some cases this image is set "directly", in other cases it’s a generated SVG. I want to be able to identify when a DIV contains the SVG-string.

My two DIVs:

<div class="cover my-1" style="background-image: url('something.jpg');">Div 1 QQ</div>
<div class="cover my-2" style="background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc...=');">Div 2</div>

And I try this:

$(document).ready(function() {
  $(".cover.my-1:contains(QQ)").css("background-color", "yellow");
  $(".cover.my-2:contains(svg+xml)").css("background-color", "yellow");  
}); 

So, DIV 1 changes as QQ is found. DIV 2 does not change as "svg+xml" is not found within the DIV-field it self (but is in the style). How do I identify the "svg+xml" in DIV 2?

I was hoping to identify the "svg+xml" within the style of the DIV

>Solution :

To identify when a DIV contains an SVG-string as a background image, you can use JavaScript to check the style attribute of the DIV and look for the "data:image/svg+xml" substring. Here’s an example

// Get all the DIVs with class "cover"
  var covers = document.querySelectorAll('.cover');
  
  // Loop through each DIV
  covers.forEach(function(cover) {
    // Check if the background image is an SVG
    if (cover.style.backgroundImage.indexOf('data:image/svg+xml') !== -1) {
      // console log if found
      console.log(cover);
    }
  });
<div class="cover my-1" style="background-image: url('something.jpg');">Div 1 QQ</div>
<div class="cover my-2" style="background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc...=');">Div 2</div>

I see you are using jQuery, so here;s the updated code for you

jQuery

$('.cover').each(function() {
    // Check if the background image is an SVG
    if ($(this).css('background-image').indexOf('data:image/svg+xml') !== -1) {
      // console log if found
      console.log($(this));
    }
  });

Leave a Reply