Click here to Skip to main content
16,016,962 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how can i get an image from the current url using javascript,i want to get an image from my current url for my site,i want to use the image somewhere any help will be appreciated.

var x = document.URL;
document.getElementByTagName("x");
var img = document.createElement("img");
img.src = x;
alert(img);


What I have tried:


var x = document.URL;
document.getElementByTagName("x");
var img = document.createElement("img");
img.src = x;
alert(img);
Posted
Comments
Bob@work 16-Nov-21 13:48pm    
If you're trying to capture the URL of an image: right click, copy image location.
If you're trying to save an image: right click, save image.
if it's something else you're after,

A few things to research -
1. x is the url of the web page running the script, not an image.
2. document.getElementsByTagName('x'); will return an array of all elements with the tag name "x". The missing 's' in the getElements... function causes an error.
3. document.getElementsByTagName('x') returns an array of elements that aren't used elsewhere in the script.
4. An image is created, but never used.
document.getElementsByTagName('x')[0].appendChild(img);
will add the image to the first element wrapped in an <x> html tag.

The following edits to your script, wrapped in an HTML page, can be used to see how the script can add an image to the page.

<html><head><title>image test&l;title>
<style>
x {border:solid 3px #dedede;
display:block;
padding:3px;
}
p{border:dashed 1px green;
}
<style>
<script>
function testImg(){
var x = document.URL;
document.getElementsByTagName("x");
var img = document.createElement("img");
img.src = x;
img.style="height:100px;width:100px;border:solid 2px red;";
alert(img);
document.getElementsByTagName('x')[0].appendChild(img);
}
<script>
<head>
<body onclick="testImg();">
<x>This is an element wrapped in an "x-tag">x>
<p>Click anywhere on the page to run the test script...>p>
<body>
<html>
Member 15440288 23-Nov-21 1:26am    
yeah you are right

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900