Use javascript selectors without jQuery to select images - javascript

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(/.+\//, '')

Related

Can you generate html locally, without using a server?

I'm trying to show images in a local html file using a loop. This is what I want it to show in the web browser:
<div id="polybridges">
<img src="polybridge_1.gif">
<img src="polybridge_2.gif">
<img src="polybridge_3.gif">
<img src="polybridge_4.gif">
<img src="polybridge_5.gif">
</div>
This is my attempt to do this with javascript:
<script>
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
</script>
<div id="polybridges">
This doesn't generate anything. Is there a way to show images in a loop without using a server / localhost?
At first your element must be defined before script execution (so change the order). I suppose you want to append elem (instead of "hallo" string):
<div id="polybridges"></div>
<script>
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
</script>
Put your images in the same directory as your html file.
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
And change the argument for appendChild.
As malix states in his comment, you should use document.getElementById("polybridges").appendChild(elem); instead of document.getElementById("polybridges").appendChild("hallo"); (so append the element instead of string "hallo").
And, as the rest states, the images should be where you tell the browser they are.
Yes you can display images without server, you have to have that images in same directory as your html file or in images folder which in same level as your html file ( for that case images would be available as <img src="images/polybridge_5.gif">
appendChild take Node as parameter (not string)
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
You need to take care of one thing. You are trying to get element by ID. So you need to make sure that html is valid. Provide proper close tag for the element. Also use the elem variable in the appendChild().
for (var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src = 'polybridge_' + i + '.gif';
console.log(elem)
document.getElementById("polybridges").appendChild(elem);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="polybridges"></div>

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
})

modify the end of an image source from 's.jpg' to 'o.jpg' with javascript

My CMS has a plugin for pulling in facebook images with stories. I cannot change it.
In the source it creates the image URL ends in s.jpg but I would like to modify it so it ends in o.jpg in order to pull in the largest photo type
This is the code:
<div class="post_picture">
<img src="http://photos-g.ak.fbcdn.net/hphotos-ak-ash3/534627_477964682254266_1412043521_s.jpg" alt="">
</div>
Is this possible? I would image you copy the source URL, modify the end from s.jpg to o.jpg and the replace the old URL w/ the new one.
EDIT:
Thanks everyone for your replies & solutions, below is another solution I found...
$('.div1>img').attr('src',function(i,e){
return e.replace("s.jpg","o.jpg");
})
ex - http://jsfiddle.net/designaroni/4Da2a/
function imgSrcOverwrite() {
var imgs = document.getElementsByTagName('img'),
loopImg, fbImgs = [];
// Loop through each IMG, check if it's a facebook image &
// then replace _s.jpg with _o.jpg in the src attribute
for ( var x=0; x<imgs.length; x++ ) {
loopImg = imgs[x];
if ( loopImg.src.indexOf('photos-g.ak.fbcdn.net') > -1 ) {
loopImg.src = loopImg.src.replace('_s.jpg', '_o.jpg');
fbImgs.push(loopImg);
}
}
imgs = loopImg = null;
// return array of fb images so you can do more stuff with them
return fbImgs;
}
imgSrcOverwrite();
If you're using jQuery I'd replace the second line with
var imgs = $('.post_picture img'),
http://jsfiddle.net/CoryDanielson/jmzk2/
Here's a quick example of how it may be possible.
// get image dom element
var img = document.getElementById('imageId');
// update src
img.src = img.src.replace(/s.jpg/, 'o.jpg');
If you are using jquery,
Try to access the img tag by this -
var src = '';
$('.post_picture').find('img').each(function(){
src = $(this).attr('src').toString().replace('_s.jpg', '_o.jpg');
$(this).attr('src',src);
});

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.

How to populate alt fields with the src of an image for all images on page

I am working on a site that has a page that will have a couple hundred thumbnails. I would like to have the filenames (the src) of the images populate the alt fields. So for example, I currently have the thumbnails as follows:
<img src="images/thumb1.jpg" />
I would like to populate the alt fields with the filename. So, the desired result would be:
<img src="images/thumb1.jpg" alt="thumb1" />
Is there a way I can automatically generate these alt tags using the images src?
Any suggestions are appreciated. Thank you for the help!
An untested, first guess, would be:
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
images[i].alt = images[i].src;
}
JS Fiddle demo.
Just to demonstrate how much easier this can be, with a JavaScript library, I thought I'd also offer the jQuery demo too:
$('img').each(
function(){
this.alt = this.src;
this.title = this.src;
});
jQuery-based JS Fiddle demo.
Edited because I'm an idiot...
I forgot to point out that you'll need to wait for the window to finish loading (or, at least, for the document.ready event), so try it this way:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i = 0; i < numImages; i++) {
images[i].alt = images[i].src;
images[i].title = images[i].src;
}
}
And change the opening body tag to:
<body onload="makeAlt">
JS Fiddle demo.
Edited to address the OP's final question:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
var newAlt, stopAt;
for (i = 0; i < numImages; i++) {
newAlt = images[i].src.split('/').pop();
stopAt = newAlt.indexOf('.');
newAlt = newAlt.substring(0,stopAt);
images[i].alt = newAlt;
images[i].title = newAlt;
}
}
JS Fiddle, though I suspect there's a far more concise way...
To get the file name you could add to David Thomas's code...
var name = images[i].getAttribute('alt').split('/');
name = name[name.length-1].split('.')[0];
So that you end up with...
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
var name = images[i].getAttribute('src').split('/');
name = name[name.length-1].split('.')[0];
images[i].setAttribute('alt') = name;
}
(Also amazingly untested)
Here it is, with some simple DOM operations and a dash of regex magic:
var imgs = document.getElementsByTagName('img');
// This will extract the file name (minus extension) from the image's `src`
// attribute. For example: "images/thumb1.jpg" => "thumb1"
var name_regexp = /([^/]+)\.[\w]{2,4}$/i;
var matches;
for ( i = 0; i < imgs.length; i++ ) {
matches = imgs[i].src.match(name_regexp);
if ( matches.length > 1 ) {
imgs[i].alt = matches[1];
imgs[i].title = matches[1];
}
}
See JSFiddle for a demo.
var images = document.getElementsByTagName("img");
var count = images.length;
for (i=0; i<count; i++){
var src = images[i].getAttribute("src");
var path = src.split("/");
var fullname = path[path.length - 1];
var name = fullname.split(".");
var result = name[0];
images[i].setAttribute("alt") = result;
}
I think the real questions you should be asking is will all this actually help my SEO, because I assume that is the reason why you would like your alt tags populated?
There is some evidence that Google is getting better at reading Javascript, but will it run the scrip before it crawls the pages and add the alt text then index the page with that alt text and consider that alt text to provide additional value outside of the keywords it already found in your file names, especially considering that it rendered the script so it will probably know that the alt is just being copied form the file name. Or will Google simply index all the html and not even bother trying to run the javascript?
I would be interested to hear any additional insight others may have on this.
I personally feel there is a low probably that this will end up helping your SEO. If you are using a content management system you should probably be looking at how to add alt text via PHP by taking the variable for the page heading or title and inserting that to the alt text.
Unless you don't care about your SEO and are really doing this for text readers, then forget everything i just said.

Categories

Resources