How to check if an element contains an image? - javascript

How do I check to see if an element contains an image. Can't I do something like this
if(document.getElementById("image").src == myImage.src)

function hasImage(element, src) {
var images = element.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
if (images[i].getAttribute("src") == src) {
return true;
}
}
return false;
}
console.log(hasImage(document.getElementById("image"), myImage.src));
If your browser supports it, you can use element.querySelector()
var img = document.getElementById("image")
.querySelector("img[src='" + myImage.src + "']");
console.log(img ? "Found" : "Not found");

Are you trying to check if an img tag with the id "image" has a src attribute equal to a different img tag? If so try the following
if (document.getElementById('image').getAttribute('src') === myImage.getAttribute('src)) {
...
}
If you just want to see if it has an src attribute at all then you can do the following
if (document.getElementById('image').getAttribute('src')) {
...
}

Related

Get Elements inside iframe which is nested inside Frame in javascript?

Edit:I'have solved the problem. You can check my comment below.
I want to get html elements of all iframes.
These iframes can be located in my main page or they can be nested iframes.
I want to get all iframes elements.
There are many example on the internet to get elements of a specific iframe by id.
For example;
Get element value inside iframe which is nested inside Frame in javascript?
But i dont want to specify main iframe id or anything like this. I want to reach all iframes.(nested or not nested)
I am very pleased if you can help me.
Thank you.
I also have an example but it can reach only top iframe on the page with specific id.
Here is my example;
var htmlDocument = document_root;
var numberOfFrame = $("iframe[id^='" + rules.frameId + "']").length;
if (numberOfFrame > 0) {
htmlDocument = $("iframe[id^='" + rules.frameId + "']")[numberOfFrame - 1].contentDocument;
formName = $("iframe[id^='" + rules.frameId + "']")[numberOfFrame - 1].id;
var iframeList = [];
iframeHTMLObjectList.push(htmlDocument);
for (i = 0; i < htmlDocument.getElementsByTagName("iframe").length; i++) {
iframeList.push(htmlDocument.getElementsByTagName("iframe")[i]);
}
for (i = 0; i < iframeList.length; i++) {
iframeHTMLObjectList.push(iframeList[i].contentWindow.document);
}
console.log(formName);
}
I've solved the problem with recursive method.
Here is my method:
function getIframeElements(htmlDocument) {
var frames = htmlDocument.getElementsByTagName("iframe");
if (frames.length > 0) {
for (var i = 0; i < frames.length; i++) {
try {
formName = frames[i].id;
getIframeElements(frames[i].contentWindow.document);
} catch (err) {
console.log(err);
}
}
}
if (!iFrameArr.includes(htmlDocument)) {
iFrameArr.push(htmlDocument);
}
return iFrameArr;
}

Replace certain img src with another via 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");
};
};

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

Javascript slideshow with caption issues

So I am having issues with captioning my slide show using a javascript, can somebody let me know as to where I am going wrong. My code stands as this:
JavaScript Document
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
var img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
if( img.attr("src") == "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.attr("src") == "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.attr("src") == "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.attr("src") == "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.attr("src") == "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
HTML document
<div class="slides">
<img id="img1" src="">
</div>
<input type="image" src="images/Next.png" id="button" onClick="javascript:moveToNextSlide()" title="Next" >
<div id ="captionbar"></div>
Also to note, that I get this error within the "inspect element":
Uncaught TypeError: Cannot call method 'attr' of null
REVISED
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
window.onload = function(){
if( img.src === "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.src === "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.src === "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.src === "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.src === "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
}
The HTML Remains the same as before.
No error references however function does not write the text whatsoever.
Replace all img.attr('src') by img.src=="your image name".
For example:
img.src=="movieImages/img1.jpg"
As you are using pure JavaScript,you cannot use attr() which is method of JQuery.
attr() is a method brought by JQuery. If you are not using JQuery, you should keep using img.src. Another thing I noticed that might cause trouble : when you read .src from your image, you get the full path as a return (including your domain).
Your conditions would then become :
img.src === "http://yourdomain.com/movieImages/img1.jpg"
( And I just checked to be sure : http://www.w3schools.com/jsref/prop_img_src.asp mentions that the return value of img.src includes protocol and domain )
Also I think you should either define your function CaptionSlide inside moveToNextSlide so that it gains access to the updated img variable or not declare your img variable inside the moveToNextSlide function (so that the global variable gets updated instead)
Another point : you should make sure the DOM is loaded before querying elements from it (such as img) . To do so, wrap your code in a function, and assign it to the window.onload event :
window.onload = function() {
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
...
}
function CaptionSlide()
{
if( ... )
...
}
document.getElementById("button").addEventListener('click', moveToNextSlide);
}
and HTML for button :
<input type="image" src="images/Next.png" id="button" title="Next" />

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

Categories

Resources