Hi i want to access all images under some specific div in javascript.My code is :
<div id="image-container" style="background-image:url(loading.gif)">
<div class="fade-box" id="image-1"><img src="2bscene-logo.gif" alt="" width="330" height="108" border="0" /></div>
<div class="fade-box" id="image-2" style="display: none;"><img src="streetgallery-logo.gif" alt="" width="330" height="108" border="0" /></div>
<div class="fade-box" id="image-3" style="display: none;"><img src="g4m-logo.gif" alt="" width="330" height="108" border="0" /></div>
</div>
While my js code is :
var image_slide = new Array('image-1', 'image-2', 'image-3');
I want to get all DIVs based on id dynamically, not having a predefined array. How can I do that?
By pure javascript, you can try:
var arr = document.querySelectorAll('#image-container img');
for(var i=0;i<arr.length;i++){
console.log(arr[i].getAttribute('src'))
}
On browsers that support querySelectorAll. (IE8 and up, modern versions of others, not IE7 and down.) - As mentioned in the comment by T.J. Crowder
With JavaScript, you can do this easily with the DOM:
var container = document.getElementById("image-container");
var child;
var image_slide = [];
for (child = container.firstChild; child; child = child.nextSibling) {
if (child.id && child.nodeName === "DIV") {
image_slide.push(child.id);
}
}
Live Example | Source
Note that the code above must be run after the elements are already in the DOM. The best way to ensure that is to put the script tag below them in the page (just before the closing </body> element is good).
Related
I Hope you can help me.
When I click button it adds night before file extension ex.(interior-1.jpg to interior-1-night) but it only affects the first image which is interior-1.jpg.
What I want is to add "night" text before the file extension of all images under the "image" ID.
Here is my html code
<button onclick="changeMode()">switch</button>
<img id="image" src="interior-1.jpg"/>
<img id="image" src="interior-2.jpg"/>
<img id="image" src="interior-3.jpg"/>
<img id="image" src="interior-4.jpg"/>
<img id="image" src="interior-5.jpg"/>
Here is my javascript code
<script>
function changeMode() {
var filename = document.getElementById("image").src;
var modfilename = filename.replace(/(\.[\w\d_-]+)$/i, '-night$1');
document.getElementById("image").src = modfilename;
</script>
}
You should never use same id name on elements in the dom. Instead use same class name. To apply the src on all the img tag get all the tags using document.getElementsByClassName. Iterate over each element and change the src using a forEach loop
function changeMode() {
var filename = document.getElementsByClassName("image");
var a = '';
Object.values(filename).forEach((e) => {
a = e.src;
var modfilename = a.replace(/(\.[\w\d_-]+)$/i, '-night$1');
e.src = modfilename;
})
}
<button onclick="changeMode()">switch</button>
<img class="image" src="interior-1.jpg" />
<img class="image" src="interior-2.jpg" />
<img class="image" src="interior-3.jpg" />
<img class="image" src="interior-4.jpg" />
<img class="image" src="interior-5.jpg" />
The problem is that you are getting your element by GetElementById which only returns one element. You should change the id tag to name like this:
<img name="image" src="interior-1.jpg"/>
Then you should be able to retrieve all the elements using var els = document.getElementsByName('image');
now you need to change their file names, so
for (let i = 0; i<els.length; i++){
els[i].src = els[i].src.replace(/(\.[\w\d_-]+)$/i, '-night$1');
}
Here is my two cents. Use classes. This way you can query multiple elements instead of just one. Then apply your changes to each element using, in this case, a forEach.
The elements returend from document.querySelectorAll is a nodeList. That's why I use Array.prototype.forEach.call.
function changeMode() {
const imageNodes = document.querySelectorAll(".image");
Array.prototype.forEach.call(imageNodes, (node) => {
let modfilename = node.src.replace(/(\.[\w\d_-]+)$/i, '-night$1');
node.src = modfilename
})
}
<button onclick="changeMode()">switch</button>
<img class="image" src="interior-1.jpg"/>
<img class="image" src="interior-2.jpg"/>
<img class="image" src="interior-3.jpg"/>
<img class="image" src="interior-4.jpg"/>
<img class="image" src="interior-5.jpg"/>
I'm trying to create a JavaScript that will randomize images on page refresh. I'm not really familiar with JS so I've been having a bit of trouble.
I've succeeded in building a successful program by hard coding the image url sources into the JS array, but this is not a possibility for what I am coding this for because the user will dictate what set of images will display. The user will not have access to the JS. So the array would get the image sources from the html. What I've been trying to do is use "getElementByClassName" and insert into the array by for loop. But it doesn't seem to be working. I'm sure there is a more efficient way to do this as well, so feel free to enlighten me.
Here is the code I have so far:
<!-- Images to put into JS Array -->
<img class="header" src="/image1.jpg" style="display: none;" />
<img class="header" src="/image2.jpg" style="display: none;" />
<img class="header" src="/image3.jpg" style="display: none;" />
<!-- Image placeholder -->
<img src="/image1.jpg" id="rotate" />
And the JavaScript in a separate document:
// Javascript code
window.onload = chooseHeader;
var imgs = document.getElementsByClassName("header");
var headers = new Array();
for (var i = 0; i < imgs.length; i++) {
headers.push(imgs[i].src);
}
function chooseHeader() {
rand = Math.floor((Math.random() * headers.length));
document.getElementById("rotate").src = headers[rand];
}
Any advice will be appreciated!
Your code is probably running before the DOM has loaded.
You don't actually need an Array for this, and since getElementsByClassName returns a "live list", you can fetch the images before they exist, and they'll appear when they're loaded in the document.
So if that's the case, a solution is to get the src directly from imgs.
window.onload = chooseHeader;
// live list
var imgs = document.getElementsByClassName("header");
function chooseHeader() {
var rand = Math.floor((Math.random() * imgs.length));
document.getElementById("rotate").src = imgs[rand].src;
}
<img class=header src="https://dummyimage.com/50/f00/fff.jpg">
<img class=header src="https://dummyimage.com/50/0f0/fff.jpg">
<img class=header src="https://dummyimage.com/50/00f/fff.jpg">
<br><br>
Rotate:
<br><br>
<img id=rotate src="">
I have a list of elements similar to simplified HTML below. When one of the images is clicked some JavaScript if fired, and the image that is clicked becomes this.theImage.
I now need to get the position of the image; for example if the first image was clicked, the position should be 1, if the second is clicked it should be 2, and so on.
I could use var elements = $('.image-preview', '#gallery');, to take a list of all elements with the image-preview class, and then loop through them and match the ID to the image, but that seems really inefficient.
Is there another way of achieving this task that is more efficient?
<div id="gallery">
<div class="image-preview">
<img id="image-1" src="http://www.mysite.com/image1.jpg" />
</div>
<div class="image-preview">
<img id="image-2" src="http://www.mysite.com/image2.jpg" />
</div>
<div class="image-preview">
<img id="image-3" src="http://www.mysite.com/image3.jpg" />
</div>
<div class="image-preview">
<img id="image-4" src="http://www.mysite.com/image4.jpg" />
</div>
</div>
Not sure I get it, you catch a click on the image like this
$('.image-preview img').on('click', function() {
});
and then to get the index you'd do
$('.image-preview img').on('click', function() {
var index = $('.image-preview img').index(this);
});
note that it's zero based
FIDDLE
You can make Array.prototype.indexOf do it for you:
var gallery = document.getElementById('gallery'),
els = [].slice.call(gallery.getElementsByTagName('img'));
gallery.onclick = function(e) {
if(e.target.tagName.toLowerCase() !== 'img') return;
var position = els.indexOf(e.target);
};
Demo
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 simple list of images that is being controlled via a CMS (ExpressionEngine). Like this:
<div class="wrapper">
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
</div>
What I want to do is for every 5 images, wrap them in a div with a class of "slide." To look like this:
<div class="wrapper">
<div class="slide">
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
</div>
<div class="slide">
<img src="#" />
<img src="#" />
<img src="#" />
</div>
</div>
The reason I am not manually coding the "" in is because of a jQuery content slider that I am using which requires every 5 images to be wrapped inside a slide div.
I'm not sure how what the code in ExpressionEngine would be to do this, but I figure it might just be easier to use Javascript to wrap every 5 images with the div. And to just have ExpressionEngine output the different images all at once.
Any help?
Here's one way:
Example: http://jsfiddle.net/T6tu4/
$('div.wrapper > a').each(function(i) {
if( i % 5 == 0 ) {
$(this).nextAll().andSelf().slice(0,5).wrapAll('<div class="slide"></div>');
}
});
Here's another way:
Example: http://jsfiddle.net/T6tu4/1/
var a = $('div.wrapper > a');
for( var i = 0; i < a.length; i+=5 ) {
a.slice(i, i+5).wrapAll('<div class="slide"></div>');
}
You can just create a div for every fith element and move the links into them using the append method:
var wrapper = $('.wrapper');
var div;
$('a', wrapper).each(function(i,e){
if (i % 5 == 0) div = $('<div/>').addClass('slide').appendTo(wrapper);
div.append(e);
});
Demo: http://jsfiddle.net/Guffa/ybrxu/
I think this would do that:
var links = $('.wrapper').children();
for (var i = 0, len = links.length; i < len; i += 5) {
links.slice(i, i + 5).wrapAll('<div class="slide"/>');
}
Try this:
$(function(){
var curDiv = null;
var mainDiv = $("div.wrapper");
$("span", mainDiv).each(function(i, b){
if(i%5 == 0) {
curDiv = $("<div class='slide'/>").appendTo(mainDiv);
}
curDiv.append(b);
});
});
You need to use jQuery slice with wrap
Check this question
Use slice() to select the element subset then wrapAll() to wrap the div around them. Here's a function that does that.
var wrapEveryN = function(n, elements, wrapper) {
for (var i=0; i< elements.length; i+=n) {
elements.slice(i,i+n).wrapAll(wrapper);
}
}
wrapEveryN( 5, $(".wrapper a"), '<div class="slide"></div>' );
Demo: http://jsfiddle.net/C5cHC/
Note that the second parameter of slice may go out of bounds, but jQuery seems to handle this automatically.