paco paco - 4 months ago 7
HTML Question

Return the string based on the source via Javascript

I have a img source on my page with no tag id to select it and would like to regex match to it and return the full URL.

The img looks like this:

<div style="display: none;">
<img src="https://suburl2.suburl1.url.com/c2/xyz/pagview?aasdasd"style="display:none" width="0" height="0">
</div>


I have tried the following JS:

var allImages = document.getElementsByTagName("img");
var target;
for(var i = 0, max = allImages.length; i < max; i++)
if (allImages[i].src =~ "https://suburl2.suburl1.url.com/c2/xyz/"){
target = allImages[i];
break;
}
console.log(allImages)


what I would like to do is have a script to iterate through all images and if the scr url contains suburl2, return the full src url.

hopefully that all makes sense.... thanks for your help

Answer

You can use document.querySelector() within attribute equals, attribute begins with or attribute contains selector to select <img> element having src attribute equal to "https://suburl2.suburl1.url.com/c2/xyz/pagview?aasdasd"

 var img = document.querySelector("img[src='https://suburl2.suburl1.url.com/c2/xyz/pagview?aasdasd']");
console.log(img.src);
<div style="display: none;">
  <img src="https://suburl2.suburl1.url.com/c2/xyz/pagview?aasdasd" style="display:none" width="0" height="0">
</div>

Comments