Replace certain img src with another via javascript - javascript

I'm trying to replace all the src for all images on my page when the src is something specific:
$("img").each(function(i, elem){
if ($(this).attr("src") == "/images/oldimage.png"){
console.log("yay!") //this doesn't log anything
$(this).attr("src", "/images/mynewimage.png");
}
});
I figured the above would work, but it doesn't seem to be. It's not finding anything that matches my if statement, which I tested with the console.log, but there are lots of img that should match.

You can use getAttribute and setAttribute to make this.
var aExample = document.querySelectorAll("img");
for(var i = 0; i < aExample.length; i += 1) {
if(aExample[i].getAttribute("src") === "images/old.png") {
aExample[i].setAttribute("src", "images/new.png");
};
};

Related

find an image name and replace it with a different source

I am writing a chrome extension to replace all the occurrences of certain set of image ( I have the image names) and replace it with another image (src)
I need to find all the occurrences of a certain image name in a website and replace the src of the image with a custom image.
I can find the image name in <img> tags with the following snippet
var key = 'img[src*="' + src + '"]';
var img = $(key);
img.attr('src', 'http://blah.blah/a.png);
Problem occurs when the image is set as background-image or as a css property.
Is it possible to scan the DOM with jQuery (recursively in all the attached style sheets) and replace all the occurrences of the image with the target url? If it is possible, can anyone point me in the right direction?
I think this could be like this, hope this will help you
$(document).ready(function(){
$("*").each(function(){
var bgImge = $(this).css('background-image');
if(bgImge.indexOf('yourImageName') > -1)
{
$(this).css('background-image', 'newImage');
}
});
});
You can change all inline background images with this:
$("[style*=background-image]").css('background-image', function(i, oldimg) {
return oldimg.indexOf(src) == -1 ? oldimg : 'url(http://blah.blah/a.png)';
});
Changing background images in the CSS is trickier.
var ss = document.styleSheets;
for (var i = 0; i < ss.length; i++) {
var rules = ss[i].cssRules;
for (var j = 0; j < rules.length; j++) {
var rule = rules[i];
if (rule && rule.type == CSSRule.STYLE_RULE && rule.style.backgroundImage.indexOf(src) != -1) {
rule.style.backgroundImage = 'url(http://blah.blah/a.png)';
}
}
}
Tested on current page, working fine.
var src = 'http://cdn.sstatic.net/stackoverflow/img/sprites.svg?v=a7723f5f7e59';
$('*').each(function(){
if( $(this).css('background-image').indexOf(src)!=-1){
console.log('Found',this);
$(this).css('background-image','url(http://blah.blah/a.png)');
}
});
You could manually run through each to check it's value:
$("*").each(function() {
var b = $(this).css("background-image") || $(this).css("background");
// check if 'b' has the image name
})

Use javascript selectors without jQuery to select images

I have some images like this:
<img src="http://127.0.0.1/test/images/cat01.png" alt="00" class="cat_img">
<img src="http://127.0.0.1/test/images/cat02.png" alt="00" class="cat_img">
<img src="http://127.0.0.1/test/images/cat03.png" alt="00" class="cat_img">
and I want to select the image names (cat01.png, cat03.png and cat03.png) with javascript (without jQuery).
How can I do that ?
I have tried :
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
console.log('Images '+images);
Thanks for help.
Or like this (no need to use Array.prototype.slice)
var images = Array.prototype.map.call(
document.querySelectorAll(".cat_img"),
function(img) {
var src = img.src,
lastIndex = src.lastIndexOf('/');
return src.slice(lastIndex + 1);
});
You can loop over your images array using map and return the part of the src attribute that you want (everything after the last /):
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
var imageNames = images.map(function( image ) {
return image.src.substring( image.src.lastIndexOf("/") + 1 );
} );
console.log(imageNames);
jsfiddle
Here is a simple example using regex with a loop.
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
for(i = 0; i < images.length; i++) {
console.log(images[i].src.replace(/.+\//, ''));
}
jsfiddle
So to build your array of names, just replace the console.log(...) line with images[i] = images[i].src.replace(/.+\//, '')

Can I access and then replace image based on src value?, using jQuery or otherwise

I have a hell CMS to work with and am wondering if i can do the following with jQuery (or just straight up JS)
images are being displayed with no ID's or classes and I'd like to replace images based on their src value
pseudo code would be something like...
find img where src = /img/00789-reg-1.jpg';
and replace src value with ='img/much-better-img.jpg';
thanks -
Each image is a part of array provided by document.images. You can loop through images to find the image with the source you need.
var index=0;
while(document.images[index]){
alert(document.images[index].src);
index++;
}
Yes you can:
jQuery('img[src=/img/00789-reg-1.jpg]').attr('src','img/much-better-img.jpg');
Could you use:
var images = document.images;
var iLength = images.length;
for (var i=0; i<iLength; i++){
thisImage = images[i];
if (thisImage.src == "theOneThatIWantToReplace"){
thisImage.src = "myNewSrc"
break;
}
}
At least this doesn't involve hefting JQuery around if you don't need it.
You can use the Attribute Starts With Selector to find your images, then do the replace:
$("img[src^='/img']").each(function(){
$(this).attr("src", "new image");
});
var replace = {
"/img/00789-reg-1.jpg": "img/much-better-img.jpg",
"/img/another.jpg": "img/another-img.jpg"
}
for (var src in replace){
$("img[src="+src+"]").attr("src", replace[src]);
}
You can get all images and then check source of it
$('img').foreach(function(o){
if (o.attr('src')=='oldfile')
o.attr('src', 'newfile');
});
This is long, but I don't know other way.

IE7 javascript error: runtime-error microsoft jscript: dropdownlist is not defined

I have another error caused by IE7 (great program...) I am trying to get a dropdownlist into a javascript function so that i can use it's values to hid some divs which are named after those values. but each time I try to use this dropdownlist I get the following error:
runtime-error microsoft jscript: dropdownlist is not defined
the javascript:
<script src="/Scripts/ShowHide.js" type="text/javascript"></script>
function ShowHideDivByDropDownList(dropdownlist) {
for (i = 0; i < dropdownlist.options.lenght; i++) {
var divId = dropdownlist.options[i].value;
if (divId != "") {
document.getElementById(divId).style.display = "none";
}
}
document.getElementById(drowdownlist.value).style.display = "block";
}
the dropdownlist:
#Html.DropDownList("MainList",
new SelectList(Model.ListCategories,
Model.List,
new { onchange ="ShowHideDivByDropDownList(this)"})
EDIT:
I have made allot of trail adjustments to try and make the script running, allot of people seem to have noticed this :). I have returned to script to it's original state, but the error still occurs.
If it's an ID use getElementById(id), if it's a name use getElementsByName(name)[0].
getElementByName doesn't exist.
Also be careful with your variable names...
In your for loop you have drowdownlish instead of drowdownlist. Just for sanity sake you may want to make those dropdownlist.
function ShowHideDivByDropDownList(dropdownlistid) {
var dropdownlist= document.getElementByName(dropdownlistid);
for (i = 0; i < dropdownlist.options.count; i++) {
var divId = dropdownlist.options[i].value;
if (divId != "") {
document.getElementById(divId).style.display = "none";
}
}
document.getElementById(dropdownlist.value).style.display = "block";
}
You can prevent yourself all this mess - as this answer correctly said, you have to use getElementById but if you change your code to this:
onchange ="ShowHideDivByDropDownList(this)"
Then you pass the actual object to the function then you can safely have such code instead:
function ShowHideDivByDropDownList(drowdownlist) {
for (var i = 0; i < drowdownlist.options.length; i++) {
var divId = drowdownlist.options[i].value;
if (divId !== "") {
var element = document.getElementById(divId);
if (element)
element.style.display = "none";
}
}
var element = document.getElementById(drowdownlist.value);
if (element)
element.style.display = "block";
}
Couple of things I fixed along the way as well:
In JavaScript, array length is .length, not .count
In case there's no element with such ID your code would crash - to avoid such mishap it's always good practice to validate you really have such element - you can add alert("element does not exist"); for debug purpose but having the whole code crash because you have typo is not a good thing.

How to replace all empty <img src=""> on a page with JavaScript on dom loaded?

I need a function, that starts, when the DOM is loaded.
In my HTML Page are several empty Image Tags, like and I want to add an Image-Name into the src-property when everything is loaded to get something like
<img src="blank.jpg">.
Best wishes
Chris
Construction <img src=""> is invalid. Never use it.
It's invalid because empty url means url to current page. But current page is HTML document, not image. Browser can make another query of current page and try to use it as image (see this page).
function replaceSrc()
{
var images = document.getElementsByTagName('img');
for(var i = 0; i < images.length; i++)
{
var img = images[i];
if(img.src.length == 0)
{
img.src = 'blank.jpg';
}
}
}
window.onload = replaceSrc;
OR if you want to add more than one handler for the event:
document.addEventListener('load', replaceSrc, false) //W3C
document.attachEvent('onload', replaceSrc); //IE
With jQuery
$(document)
.ready(function() { $('img')
.filter(function(){ return this.src.length == 0 })
.each(function () { this.src = 'blank.jpg'}) });
EDIT:
I realized that you probably want to set the src property before the images load so I changed the code to fire on the document's load event, which happens before the images start loading.
Use jQuery! It's easy.
$('img').attr('src','new-image-name.jpg')
This will set the src attribute of every img tag to 'new-image-name.jpg'.
With jQuery, this would set the src attribute of all img elements with a blank src attribute to "blank.jpg" on page load.
$.ready(function() {
$("img[src='']").attr("src", "blank.jpg");
});
You can use this script.
# Script AddImage.txt
var string pagefile, image, html
# Read in the page file.
cat $pagefile > $html
# Replace all instances of "<img src="blank.jpg">" with the specified image.
while ( { sen -r -c "^<img src=&\>^" $html } > 0 )
sal -r -c "^<img src=&\>^" ("<img src=\""+$image+"\">") $html > null
# Write page back.
echo $html > { echo $pagefile }
Script is in biterscripting. Save the script in file "C:/Scripts/AddImage.txt", run it with this command.
script "C:/Scripts/AddImage.txt" pagefile("/path/to/page.html") image("blank.jpg")
It will replace previous image with "blank.jpg".
With JQuery you can simply solve your problem using following code.
$(function(){
$("img[src='']").attr("src", "blank.jpg");
});
Replace images if null from API data using dom manipulation
const images = document.getElementsByTagName('img');
for(const img of images){
const src = img.getAttribute('src');
if(src === "null" && strGender === "Male"){
img.src = "img/placeholder-male.jpg";
} else if(src === "null" && strGender === "Female"){
img.src = "img/placeholder-female.jpg"
}
}

Categories

Resources