I'm trying to load an array filled with the src attribute from a series of img tags in my HTML document.
HTML:
<html>
<head>
<title>
JQuery Slider
</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<div id = "wrapper">
<h1 class="dark-header">2014 Salt Lake Comic Con FanX</h1>
<div id="background-img">
<img src="img/img01.jpg"/>
</div>
<div>
<img src="img/img02.jpg"/>
</div>
<div>
<img src="img/img03.jpg"/>
</div>
<div>
<img src="img/img04.jpg"/>
</div>
<div>
<img src="img/img05.jpg"/>
</div>
<div>
<img src="img/img06.jpg"/>
</div>
<div>
<img src="img/img07.jpg"/>
</div>
<div>
<img src="img/img08.jpg"/>
</div>
<div>
<img src="img/img09.jpg"/>
</div>
<div>
<img src="img/img10.jpg"/>
</div>
</div>
</body>
</html>
JQuery:
$(document).ready(function() {
var source = new Array();
$('img').each(function(attr) {
source.push($('img').attr('src'))
});
console.log(source)
});//end document.ready
The output to the console is an array of 10 elements, but only using the first img attribute. I'm not sure how to get the each function to go through all elements and push them to the array.
Your issue is that $('img').attr('src') will always return the value of the first element in the collection of elements.
As pointed out in comments , you need to look at specific instances within your loop
Another way you can do this is using map() which will create the array for you
var source = $('img').map(function(){
return $(this).attr('src');
}).get();
DEMO
You could try something like this:
var source = [];
$('img').each(function() {
source.push( this.getAttribute('src') );
});
In your each code, you re-select the entire group with $('img') so it is only adding the first one of THAT Selection to your array.
OR
If you aren't using jQuery for anything else, you could do it in straight javascript like this:
document.addEventListener('DOMContentLoaded', getImgAttr);
var source = [];
function getImgAttr() {
var imgs = document.querySelectorAll('img');
[].forEach.call(imgs, function( img ) {
source.push( img.src);
});
}
you need to use 'this' while inside the loop to reference the image, otherwise you are getting the reference to first 'img ' tag.
it should be like this:
$('img').each(function(attr) {
source.push($(this).attr('src'))
});
Your callback function needs to accept a second param...
The first param is the current index of the array and the second param is the object at that index.
You may also utilize the keyword this as suggested above.
Based on my answer your code would look like this:
$('img').each(function(i, img) {
source.push($(img).attr('src'));
// alternatively -> source.push($(this).attr('src'));
});
A second option you may like and puts what you're trying to do onto a single line would be to use the jQuery map function...
var source = $.map($('img'), function(img) { return $(img).attr('src'); });
Related
i have some project that need to change multiple iframe with some array
example
<ul>
<li>
<iframe src="test.html">
<head></head>
<body>
<div class="content">
<p>test</p>
</div>
</body>
</iframe>
</li>
<li>
<iframe src="test.html">
<head></head>
<body>
<div class="content">
<p>test</p>
</div>
</body>
</iframe>
</li>
</ul>
I need to change <div class="content"><p>test</p></div> for each iframe with an array ["<h1>tittle</h1>","<h1>tittle2</h1>"].
For the first iframe it will be replaced with the HTML in array[0] and second iframe with array[1].
Can anyone help? Thanks
Try with replaceWith()
var array = ["<h1>tittle</h1>", "<h1>tittle2</h1>"]
$(document).ready(function() {
$('iframe').load(function() {
$('iframe').each(function(a) {
$(this).contents().find('body').children('.content').replaceWith(array[a]);
})
})
})
Here you go :
var arr = ["<h1>tittle</h1>","<h1>tittle2</h1>"];
var found=0;
$('iframe').each(function(){
if($(this).find('.content p').length > 0){
$(this).find('.content p').parent().replaceWith(arr[found]);
found++;
}
});
It searches for every iframe, then checks if it contains the tags you want, then replaces them with your array's replacement.
The variable 'found' allows you to travel through the array.
As much as you tagged your post with "jQuery", I suppose you can use this library.
So you just need to iterate over the .each() function.
var array = ["<h1>tittle</h1>","<h1>tittle2</h1>"];
$(".content").each(function(i) {
$(this).html(array[i]);
});
You can obviously replace html() with replaceWith() if you really want to delete the div.
You could try this:
var iframe = $('iframe');
for (i=0; i<iframe.length; i++){
var current = $('iframe')[i+1].contentWindow.document.body.innerHTML;
$('iframe')[i].contents().find('html').html(current);
}
EDIT: Here's the JSFiddle for the following question.
http://jsfiddle.net/x28ojg6w/
So I'm trying to activate a template with JavaScript and it wasn't working for a while, and I finally fixed it by changing a For-In loop into a For loop in a seemingly unrelated block of code.
The following code is the For-In loop I changed to a for loop. The commented out code was the original code that didn't work and the uncommented for loop is the now working code. This code was used to change font size for text within all instances of a class element:
var release4 = document.getElementsByClassName("release-4");
// for (item in release4){
// release4[item].style.fontSize = "2em";
// };
for (var i = 0 ; i < release4.length ; i++) {
release4[i].style.fontSize = "2em";
}
This is the code I used to activate my template. It is not part of the release-4 class:
var tmpl = document.getElementById('hidden');
document.body.appendChild(tmpl.content.cloneNode(true));
And here is the HTML that goes with it:
<html>
<head>
<title>Manipulate the DOM</title>
</head>
<body>
<div id="release-0">
<p class="release-4"> Here is some text, add a class "done" to the parent div</p>
</div>
<div id="release-1">
<p>remove the #release-1 div</p>
</div>
<h1>Change this text to finish release 2</h1>
<div id="release-3">
<p class="release-4"> add CSS to this div</p>
</div>
<template id="hidden">
<div>
<h1> Congrats! You finished the challenge.</h1>
<img src="http://media.giphy.com/media/2UpzC3iPenf44/giphy.gif">
</div>
</template>
<script type="text/javascript" src="home_page.js"></script>
</body>
</html>
My question is why did changing the For loop make a difference? Thanks everyone!
All other code in the JS file only affect IDs release-0, release-1, and release-3, and the h1 tag. The class name, display, innerHTML, and background color were the only changes made to them.
If I console.log() item in the for in loop it yields:
0
1
length
item
namedItem
I think length, ìtem and namedItem make it error.
Updated:
With Array.from it works as expected.
var release4 = Array.from(document.getElementsByClassName("release-4"));
for (item in release4){
release4[item].style.fontSize = "2em";
};
Sorry if this is a silly question, but I've been trying to use AJAX to display my javascript variables in 'real time' with little luck. I'm definitely a beginner though so this could be the problem haha- When I see the AJAX code, it always seems to require an additional url that it refreshes, but I just want to refresh the javascript variables on click.
http://jsfiddle.net/bagelpirate/m9Pm2/
<script>
var one = 0;
var two = 0;
var three = 0;
</script>
<body>
<div id="div_1">
One: <script>document.write(one)</script> |
Two: <script>document.write(two)</script> |
Three: <script>document.write(three)</script>
</div>
<div id="div_2">
<img id="mine" src="https://si0.twimg.com/profile_images/3170725828/ac1d6621fc3c3ecaa541d8073d4421cc.jpeg" onclick="one++;" />
<img id="forest" src="http://blogs.dallasobserver.com/sportatorium/No.%202.png" onclick="two++;" />
<img id="farm" src="https://si0.twimg.com/profile_images/3732261215/bd041d1f0948b6ea0493f90507d67ef2.png" onclick="three++;" />
</div>
</body>
As you can see in the above code, when a user clicks one of the images, I want to increment the count and display it at the top of the page. I found the HTML5 output tag, and was wondering if it's possible to use this to display the javascript variable in real time? Everything I've read seems to imply it can't be done because the output tag only works on forms? Anyway, I figured it couldn't hurt to ask!
Thanks for your time!
You shouldn't use document.write to write to the DOM after it's finished loading. You have tagged your question with jQuery, so I'll assume you can use that to update things. Instead, update the DOM from within your script block. Here is an example that might help you get started.
http://jsfiddle.net/prxBb/
<script type="text/javascript">
$(function() {
var one = 0;
var two = 0;
var three = 0;
$('img#mine').click(function() {
one++;
$('span#one').html(one);
});
$('img#forest').click(function() {
two++;
$('span#two').html(two);
});
$('img#farm').click(function() {
three++;
$('span#three').html(three);
});
});
</script>
<body>
<div id="div_1">
One: <span id="one"></span> |
Two: <span id="two"></span> |
Three: <span id="three"></span>
</div>
<div id="div_2">
<img id="mine" src="https://si0.twimg.com/profile_images/3170725828/ac1d6621fc3c3ecaa541d8073d4421cc.jpeg" />
<img id="forest" src="http://blogs.dallasobserver.com/sportatorium/No.%202.png" />
<img id="farm" src="https://si0.twimg.com/profile_images/3732261215/bd041d1f0948b6ea0493f90507d67ef2.png" />
</div>
</body>
Maybe you should try putting all your variables inside a named object, iterating through it at predefined interval and displaying the values.
var varContainer = {
one:0,
two:0,
three:0
};
jQuery("#div_2 img").on('click',function(){
jQuery.each(varContainer,function(key,value){
//Add key + value to the DOM
if(jQuery("."+key+value).length<1)
jQuery("#div_2").append("<div class='"+key+value+"'></div>");
var newHtmlVal= "<p><span>Var name: "+key+"</span><br><span>Value: "+value+"</span>";
jQuery("."+key+value).html();
});
});
HTML
<div id="div_2">
</div>
Of course the script could be upgraded to look through each variable recursivley in case of nested objects/arrays...
Hope this helps!
In jQuery or JS I need to count the amount of DIV elements inside my parent DIV called cont? I've seen similar questions here on StackOverflow and have tried the following.
<div class="b-load" id="cont">
<div>
<img src="page2.jpg" alt=""/>
</div>
<div>
<img src="page3.jpg" alt="" />
</div>
<div>
<img src="page4.jpg" alt="" />
</div>
<div>
<img src="page5.jpg" alt="" />
</div>
</div>
function countPages() {
var maindiv = document.getElementById('cont');
var count = maindiv.getElementsByTagName('div').length;
alert(count);
}
The child DIV's are dynamically produced, so I need to count them after the page has finished loading. The problem I have is the function I wrote counts 13 DIV's and in this example, there should only 4!! Any help gratefully received..
console.log($("#cont div").length);
var maindiv = document.getElementById('cont');
var count = maindiv.children.length;
alert(count);
Try this
$(function(){
var mainDiv = $('#cont');
var childDivCount = mainDiv.find('div').length;
});
By the way, this is jQuery's syntax (one of them anyways) for document ready. This will only fire after your page has completed loading.
No need to use jQuery here. If you only need to know the amount of childElements, you can use node.childElementCount
i have a list of images
<img src="image-1.jpg" />
<img src="image-2.jpg" />
<img src="image-3.jpg" />
<img src="image-4.jpg" />
<img src="image-5.jpg" />
whats the best way to reorder them such that image-1 is at the bottom? (but not necessarily image-1)
Edit: Preferably without using anything like the JQuery UI.
I would like this to be done with as little code as possible.
Simple and easy
$(function(){
var parent=$("img").parent();
$("img:first").appendTo(parent);
});
If you are not trying to create a dynamic sortable list and are just looking for a way to re-order images. You could try the following.
$("img[src$='image-1.jpg']").insertAfter("img[src$='image-5.jpg']");
This will allow you to find images and move them around based on the src of the image.
http://api.jquery.com/category/manipulation/
Look at the different methods that are available for DOMinsertion.
You can achieve this by using the jQuery UI:
http://jqueryui.com/demos/sortable/
(Supposing you want this to be dynamic, if not you should further explain the exact situation)
Then you want like something this? It sorts 1,2,3,4,5 to 5,4,3,2,1
<div id="reorder">
<img src="http://www.google.com.tr/images/srpr/logo3w.png" />
<img src="http://l.yimg.com/a/i/ww/met/logo/20100909/yahoo_logo_tr.png" />
<img src="http://www.rev2.org/wp-content/uploads/2009/06/bing-logo.png" />
<img src="http://a.l.yimg.com/a/i/us/sch/yhs4/altavista_logo.png" />
<img src="http://searchcdn.infospace.com/Dogpile-8.0.1.353/Content/Img/img_trans.gif?av=1353" />
</div>
<script>
$(function() {
$('#reorder').click(function() {
$("#reorder").randomize("img");
});
});
(function($) {
var onerandom = Math.random();
$.fn.randomize = function(childElem) {
return this.each(function() {
var $this = $(this);
var elems = $this.children(childElem);
elems.sort(function() { return (Math.round(onerandom)-0.5); });
$this.remove(childElem);
for(var i=0; i < elems.length; i++)
$this.append(elems[i]);
});
}
})(jQuery);
</script>