Reputation: 3779
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.
Upvotes: 2
Views: 18017
Reputation: 76880
i'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;
}
});
Upvotes: 6
Reputation: 3709
// find all img's without the siteURL, and add it
$('img:not([src^="http://url.com"])').each(function(i){
this.src = siteURL + this.src;
});
Upvotes: 3
Reputation: 41246
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.
Upvotes: 5
Reputation: 409
Please take a look at :contains() Selector.
http://api.jquery.com/contains-selector/
Upvotes: -1
Reputation: 219936
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;
}
Upvotes: 1