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
4
Answers
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
I see you are using jQuery, so here;s the updated code for you
jQuery
:contains
works only for the content of the element. You can usefilter
andincludes
to select your items with svg backgroundIf you know upfront that you
svg+xml
is always going to be in thestyle
attribute, you could use the[attr*=value]
attribute selector. This will check ifvalue
is present inattr
.This code worked for me.
This will be turning the text color into red if it contains
data:image/svg+xml
and it will change the text color to black in casedata:image/svg+xml
is not available in the background-url linkHope this example will be helpful to you