I am looking to use jQuery contains to run through each image on a page and check if the src tag contains a certain http value. How would I run a check on the text in the src attribute with jQuery or javacript. I have the overview of what I am attempting below:
$('img').each(function(i){
var img = $(this),
imgSrc = img.attr('src'),
siteURL = "";
if(!imgSrc.contains(siteURL)){
imgSrc = siteURL + imgSrc;
}
});
I have a feeling regex may be the way to go just don't know how for sure.
I am looking to use jQuery contains to run through each image on a page and check if the src tag contains a certain http value. How would I run a check on the text in the src attribute with jQuery or javacript. I have the overview of what I am attempting below:
$('img').each(function(i){
var img = $(this),
imgSrc = img.attr('src'),
siteURL = "http://url.com";
if(!imgSrc.contains(siteURL)){
imgSrc = siteURL + imgSrc;
}
});
I have a feeling regex may be the way to go just don't know how for sure.
Share Improve this question edited Mar 2, 2016 at 3:02 L84 46.3k59 gold badges181 silver badges259 bronze badges asked Aug 31, 2011 at 17:56 jeffreynoltejeffreynolte 3,77911 gold badges42 silver badges65 bronze badges 2- Just so you know $.contains Is not for strings, it is for elements. You check if one element is contained within another, not if a string is contained within another. – Chad Commented Aug 31, 2011 at 18:00
- Thank you @Chad, yes I realize i posted the wrong link. – jeffreynolte Commented Aug 31, 2011 at 18:39
5 Answers
Reset to default 6i'd do (using indexOf):
$('img').each(function(i){
var imgSrc = this.src;
var siteURL = "http://url.com";
if(imgSrc.indexOf(siteURL) === -1){
imgSrc = siteURL + imgSrc;
}
});
Why not simply make a selector to do that?
$('img[src*="http://url.com"]')
That should select just the elements with that text in the src tag, without you having to write custom logic.
// find all img's without the siteURL, and add it
$('img:not([src^="http://url.com"])').each(function(i){
this.src = siteURL + this.src;
});
You'll want to search your imgSrc
string if it has the siteURL
string in it.
The indexOf
method returns the position of the substring within the main string. If it's not found, it returns -1
:
if (imgSrc.indexOf(siteURL) == -1) {
imgSrc = siteURL + imgSrc;
}
Please take a look at :contains() Selector.
http://api.jquery.com/contains-selector/