How to get all img and its attributes? - javascript

`
<ul class="flickr-badge-content">
<li class="first">
<img data-photo-attribution="andysouthwales" data-photo-page="http://www.flickr.com/photos/andysouthwales/1212121/" data-photo-title="abcd" data-photo-id="1212121" src="http://farm3.static.flickr.com/2855/1212121_ce6bfd5c38_s.jpg"></img>
</li>
<li>
<img data-photo-attribution="andysouthwales" data-photo-page="http://www.flickr.com/photos/andysouthwales/1263324993173/" data-photo-title="tennn" data-photo-id="1263324993173" src="http://farm8.static.flickr.com/7457/1263324993173_0e3e9745f8_s.jpg"></img>
</li>
<li>..............</ul>.......
I want to get all image and their attributes. Please Help...

You can cycle through all of the images attributes by using
$('img').each(function(currentImage){
console.log(currentImage.data('photo-attribution')); //log some attribute
});
I'm sure that you will figure the rest out.

I have provided you an example which selects all the image tag and gets the source attribute of each of them. You can use this to get whichever attribute you want.
Using JavaScript
var images = document.getElementsByTagName('img');
var srcList = [];//This is just for the src attribute
for(var i = 0; i < images.length; i++) {
srcList.push(images[i].src);
}
Instead of document.getElementsByTagName('img') you could also use the document.images collection.
function allSrc() {
var src = [];
var imgs = document.images;
for (var i=0, iLen=imgs.length; i<iLen; i++) {
src[i] = imgs[i].src;
}
return src;
}
Using Jquery:
var srcList = $('img').map(function() {
return this.src;
}).get();

try
$(document).ready(function () {
var images = $("img");
for (i = 0; i < images.length; i++) {
alert($(images[i]).attr("data-photo-attribution"));
}
});

There you go:
$('.flickr-badge-content li img').each(function(){
var data = $(this).data();
for(var i in data){
$('<li>', {
text: i + ': ' + data[i]
}).appendTo('.flickr-badge-content');
}});
Working Fiddle

Related

I'm trying to make a div width expand once clicking on another div

Im trying to make a div expanded once you click on another div. In my case I'm try to make div with some text in it expand when the image is clicked. A link to my JSFiddle - https://jsfiddle.net/txoyuvqn/3/
My javascript that I am using looks like.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '500px'
whattochange[i].style.transition = 'all 1s'
whattochange[i].style.backgroundColor = 'red'
}
}, false);
However when I click on the class called image it effects all the Text classes, i know it's because were changing the css to all of the text divs, however is there a way to make it only effect the correlating div? Or am I going about creating this in the wrong way?
getElementsByClassName returns an array, not a single element.
divs is an array, and you are correctly using a for loop and the index indicator [i] after your variable name divs.
You need a similar for loop for whattochange.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
There may be a better way, but you could do it like this:
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
{
divs[i].addEventListener("click", function()
{
var w = document.getElementById(this.id.replace('img', 'text'));
w.style.width = '800px'
w.style.transition = 'all 1s'
w.style.backgroundColor = 'red'
});
whattochange[i].id = 'text' + i;
divs[i].id = 'img' + i;
}
See the fiddle
Javascript
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
}
You have to be sure that the elements exist if your JavaScript code depends on them. The reason why your fiddle didnt work was because, you was not loading the script after the body has finished loading.
In your code, One way of achieving this is by putting the <script> tag at the end of the body like this:
<html>
<head></head>
<body>
<script type="text/javascript">
// code here
</script>
</body>
You can also put all your code in a function for the window.onload event or use jQuery.

Jquery: Show/Hide Div broken

Scenario: I'm trying to create a script that allows a user to click a thumbnail image and display a larger image in preview box. I'm using a div and a img for this example just as a placeholder for now.
Question In Jquery, is there a way to use a function with parameters as a callback for a onclick event listener? I've looked at addEventListener and Onclick and .on method in jquery, but nothing seems to fit what i'm searching for.
My Attempts:
http://jsfiddle.net/davideugenepeterson/9emhuzw0/3/
http://jsfiddle.net/EhtrR/931/
Javascript:
var numberOfImages = 4;
var imageArray = [];
//since i'm going to hide all other divs each time a img is clicked,
// I need to be calling from imageArray[] so I can difArray check later
for (i = 0; i <= numberOfImages; i++) {
//counting starts from zero, but frontend already built their naming convention to start with 1
if (i === 0) {
continue
}
imageArray.push(i);
}
for (i = 0; i <= imageArray.length; i++) {
if (i === 0) {
continue
}
//on each img click show corresponding div and hide all others, not working
$("#img-" + imageArray[i]).on('click', function () {
$("#div-" + i).show();
});
}
Another solution (four variations)
a)
// JavaScript
var img = document.getElementsByTagName('IMG'),
div= document.getElementsByTagName('DIV'),
current, i;
for(i = 0; i < img.length; i++){
(function(i){
img[i].onclick = function(){
div[i].style.display = 'block';
if(current) current.style.display = 'none';
current = div[i];
};
})(i);
}
b)
var img = document.getElementsByTagName('IMG'),
div= document.getElementsByTagName('DIV'),
current, i;
for(i = 0; i < img.length; i++){
(function(i){
img[i].onclick = function() { callback(i); };
})(i);
}
function callback(i){
div[i].style.display = 'block';
if(current) current.style.display = 'none';
current = div[i];
}
c)
var img = document.getElementsByTagName('IMG'),
div= document.getElementsByTagName('DIV'),
current, i;
for(i = 0; i < img.length; i++){
img[i].onclick = callback.call(this,i);
}
function callback(i){
return function () {
div[i].style.display = 'block';
if(current) current.style.display = 'none';
current = div[i];
};
}
<!-- HTML -->
<style>
div {display:none;}
</style>
<img src="01.jpg" alt="" />
<img src="02.jpg" alt="" />
<img src="03.jpg" alt="" />
<img src="04.jpg" alt="" />
<img src="05.jpg" alt="" />
<div>first</div>
<div>second</div>
<div>third</div>
<div>fourth</div>
<div>fifth</div>
Working jsBin
d) jQuery version
(function(){
var div = $('div'), current;
$('img').each(function(index){
$(this).bind ('click', function(){
$('div:nth(' + index + ')').show();
if(current) current.hide();
current = $('div:nth(' + index + ')');
});
});
})();
Working jsBin
I don't understand what you're trying to do with an array. Give the image something relating to a corresponding element you want to be shown (I used data attribute in example).
And give a collective class name to all the elements that are going to be shown/hidden.
Then on click, hide all and show the one related to what was clicked.
$('img').click(function(){
$('.somename').hide();
$('#div-'+$(this).data("number")).show();
});
See fiddle: fiddle

Replace an image wherever it is used - Javascript

I'm looking for a way to replace an image that could be used anywhere on a page.
So if we have an example html page like this:
<html>
<head>
</head>
<body>
<img id="1" src="example.com/img/1889.png">
<div style="background: url('example.com/img/1889.png')">
<div>
<a>
<img id="2" src="example.com/img/1889.png">
</a>
</body>
</html>
Where ever - example.com/img/1889.png - appears, it must be replaced with something else.
EDIT
Unfortunately I can't use any javascript libraries. Its for a browser plugin. Nor can I use browser specific APIs
There might be some syntax errors here, but basically just try something like:
<script>
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].src == "oldImg")
imgs[i].src = "newImg";
}
}
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if (divs[i].style.backgroundImage == "oldImg")
divs[i].style.backgroundImage = "newImg";
}
}
</script>
The following code does what you're looking for:
var images = document.querySelectorAll('[src]'), // all image and input elements
styled = document.querySelectorAll('[style]'), // all elements with inline style
iLen = images.length,
sLen = styled.length,
url = 'example.com/img/1889.png', // the string you're searching for
str = 'some/string', // replace with whatever you choose
i;
// check for 'example.com/img/1889.png' in image source
for (i = 0; i < iLen; i += 1) {
if (images[i].src.indexOf(url) !== -1) {
images[i].src = str;
}
}
// check for 'example.com/img/1889.png' in either background or background-image
for (i = 0; i < sLen; i += 1) {
if (styled[i].style.backgroundImage.indexOf(url) !== -1) {
styled[i].style.backgroundImage = 'url(' + str + ')';
}
}
Demo

javascript add relative path to all links dynamically

I'm trying to build a html file to prepend and replace string.
for example, if my url for css file,
<link href="/srsstore/store/-1/common/components/cbsassets/styles/iPhone.css" type="text/css" rel="stylesheet" />
And url for image file,
<img src="/s/store/-1/ProductizedWidgets/transparent.png" width="1px" height="1px"/>
Also, for background image
<div style="background-color: #e45600;background-image: url(/s/store/4812610/no_preview.gif);background-repeat:repeat-x;font-weight:bold;font-family:Helvetica, Arial, sans-serif; font-size:12px;color:#FFFFFF></div>
and I want to prepend "domain.com" to these urls. How do i search and replace a string dynamically using javascript.
The content is getting from this url:
http://euroleagueiphone.mo2do.net/s/31653/Home?ebbLinkIndex=0&backTitle=Home&iPhoneMode=app&debugRender=true&appVersion=2.2&engineVersion=1.3
You can try this:
window.onload = function() {
var domain = 'YOUR_DOMAIN';
// For images
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].setAttribute("src",domain + imgs[i].getAttribute("src"));
}
// For CSS files
var links = document.getElementsByTagName("link");
for (var i = 0; i < imgs.length; i++) {
links[i].setAttribute("href",domain + links[i].getAttribute("href"));
}
};
Edit:
For the divs add the following code to the above:
// For CSS files
var styleProp = 'background-image';
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if(divs[i].currentStyle) {
divs[i].style['styleProp'] = domain + divs[i].currentStyle[styleProp];
} else if (window.getComputedStyle) {
divs[i].style['styleProp'] = domain + document.defaultView.getComputedStyle(divs[i],null)
.getPropertyValue(styleProp);
}
}
You can get help form Get Styles.
$("img").each(function(){
$e = $(this);
$e.attr("src","http://example.com" + $e.attr("src"));
})
$("link").each(function(){
$e = $(this);
$e.attr("href","http://example.com" + $e.attr("href"));
})
Use jquery
You need to find all the a's and img's in your code, loop through them, get the current attribute value (whether src or href), prepend your domain to it, and then set the attribute value. I haven't tested this, but this is the general idea:
var links = document.getElementsByTagName("a");
var images = document.getElementsByTagName("img");
for (i=0; i < links.length; i++) {
links[i].setAttribute("href","domain.com" + links[i].getAttribute("href"));
}
for (i=0; i < images.length; i++) {
images[i].setAttribute("src","domain.com" + images[i].getAttribute("src"));
}

Extract image src from the whole div using Javascript

Hi I am working in JavaScript. My code is:
<div id="myDiv" onClick="myfn()">
<img src="a.png">
<img src="b.png">
</div>
I want to get the source of the images and store it in the array on click of a button.
Any help ???
myfn() {
var a = new Array();
var mainDivData = document.getElementById('myDiv').innerHTML;
var mainDivData2 = mainDivData.getElementByTag('src');
for(var i =0 ; i<mainDivData2.length; i ++) {
//a[i] = mainDivData2;
alert(a[i]);
}
}
But nothing shown in the alert even alert window doesn't opened.
Any help ???
Pure JavaScript solution:
var imgs = document.getElementById("myDiv").getElementsByTagName("img"),
arr = [];
for (var i = 0; i < imgs.length; i++) {
arr.push(imgs[i].src);
}
console.log(arr);
jQuery solution:
var arr = $("#myDiv img").map(function() {
return this.src;
}).get();
console.log(arr);

Categories