JS can't delete all images from page - javascript

I'm trying to delete all images from page. The page is in HTML. This is my HTML button:
<input id="clickMe" type="button" value="Delete Images" onclick="click();" />
And the function is:
<script type="text/javascript">
function click(){
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].Node.removeChild(images[0]);
}
}
</script>
All elements are tagged "img"

Removing a child can only be done from the parent:
function removeImages() {
var images = [].slice.call(document.getElementsByTagName('img'), 0); // get the images as array like object, and turn it into an array using slice
images.forEach(function(img) { // iterate the images array
img.parentNode.removeChild(img); // remove the child node via the parent node
});
}
<button type="button" onclick="removeImages()">Remove Images</button>
<div>
<img src="http://static.wixstatic.com/media/60d837_94f714500a3145a1b98efd7a6fe78ce7~mv2_d_3456_3456_s_4_2.jpg_256" />
<img src="https://static-s.aa-cdn.net/img/ios/442131982/82d94c67fc3d8eb87e07d9bb568c5d4d?v=1" />
<img src="https://pbs.twimg.com/profile_images/625769159339737088/2dwpQAXA.jpg" />
</div>
You can also use img.remove() instead of the cumbersome img.parentNode.removeChild(img), but it won't work in IE - see ChildNode.remove() on MDN.

You cannot have click as the function name because click is a reserved js method.
For deleting you just need to use delete() on that node.
<script type="text/javascript">
function c(){
var images = document.getElementsByTagName('img');
for (var i = images.length - 1; i >= 0; i--) {
images[0].parentNode.removeChild(images[0]);
}
}
</script>
<img src="http://unsplash.it/200/300/"/>
<img src="http://unsplash.it/200/300/"/>
<img src="http://unsplash.it/200/300/"/>
<img src="http://unsplash.it/200/300/"/>
<img src="http://unsplash.it/200/300/"/>
<input id="clickMe" type="button" value="Delete Images" onclick="c()"/>

Few inputs:
click function will never get fired as it is reserved and take precedence over the click() handler attached to onclick event. Change the handler name to something meaningful.
Use querySelectorAll to find the img elements. It returns a non-live NodeList of all elements descended from the element on which it is invoked that match the specified group of CSS selectors.
the code images[i].Node.removeChild(images[0]); is not correct as we should remove the element from the parentNode; Indexing was not correct (images[0])
function deleteImages() {
// query non-live NodeList of all `img` elements
var images = document.querySelectorAll('img');
// Loop through each `image` object.
Object.values(images).forEach(function(element, index, array) {
element.parentNode.removeChild(element);
});
}
img {
width: 200px;
height: 200px;
margin: 5px;
}
<div>
<div>My List of ducks</div>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Tufted_duck_%28aythya_fuligula%29.JPG/120px-Tufted_duck_%28aythya_fuligula%29.JPG" />
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Tufted_Duck_pangolakha_Wildlife_Sanctuary_East_Sikkim_India_27.03.2016.jpg/120px-Tufted_Duck_pangolakha_Wildlife_Sanctuary_East_Sikkim_India_27.03.2016.jpg" />
</div>
<div>
<div>My List of Flowers</div>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Lillium_Stamens.jpg/300px-Lillium_Stamens.jpg" />
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/Crateva_religiosa.jpg/220px-Crateva_religiosa.jpg" />
</div>
<input id="clickMe" type="button" value="Delete Images" onclick="deleteImages();" />

Related

Beginner/ I try to use Onclick to unhide element but it doesn't work

I want to make a page to upload the avatar.
By default, I use the vector to show where the image will appear
and then provide a button to upload the URL to change the avatar.
That's all it is! But the script still doesn't work.
Pleased to hear your feedback on how to fix it. Bless
<img id="put_image_here_bitch" src="https://cdn0.iconfinder.com/data/icons/finance-vol-2-4/48/77-512.png" alt="" width="100px" height="100px">
<div class="block" > The person who uploads this is cool
</div>
<button onclick="hideElement()">Click to upload photo by URL</button>
<div>
<input id="input" autofocus class='hidden_element' style="display: none;" type="text" id="input">
</div>
<div>
<button class='hidden_element' style="display: none;" onclick="uploadImage()">UPLOAD</button>
</div>
This is my script
function hideElement(){
var hide = document.getElementsByClassName('hidden_element');
if (hide.style.display === "none") {
hide.style.display = "block";
} else {
hide.style.display = "none";
}
}
var uploadImage = function(){
image = document.getElementById('input').value;
showImage = document.getElementById('put_image_here_bitch').setAttribute('src', image);
};
As stated in the comments, .getElementsByClassName() returns a collection of elements, not a single element and your code attempts to call the style property of the collection, which doesn't exist.
Instead, you need to loop through the collection and operate on the elements within the collection individually, but don't use .getElementsByClassName() and instead use .querySelectorAll().
var hidden = document.querySelectorAll('.hidden_element');
function hideElement(){
// Loop over the colleciton elements
hidden.forEach(function(element){
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
});
}
var uploadImage = function(){
image = document.getElementById('input').value;
showImage = document.getElementById('put_image_here_bitch').setAttribute('src', image);
};
<img id="put_image_here_bitch" src="https://cdn0.iconfinder.com/data/icons/finance-vol-2-4/48/77-512.png" alt="" width="100px" height="100px">
<div class="block" > The person who uploads this is cool
</div>
<button onclick="hideElement()">Click to upload photo by URL</button>
<div>
<input id="input" autofocus class='hidden_element' style="display: none;" type="text" id="input">
</div>
<div>
<button class='hidden_element' style="display: none;" onclick="uploadImage()">UPLOAD</button>
</div>
But, beyond that, you should also avoid using inline styles as they are the most specific way of setting a style and therefore the hardest to override. They also often require duplicated code to be written. Instead, use CSS classes as shown below:
// Get references to the DOM elements that you'll need to work with
const btnUpload = document.querySelector("button"); // find the first button
const hidden = document.querySelectorAll(".hidden");
const upload = document.querySelector(".upload");
// Do your event binding in JavaScript, not in HTML
btnUpload.addEventListener("click", hideElement);
upload.addEventListener("click", uploadImage);
function hideElement(){
// Loop over the collection of hidden elements
hidden.forEach(function(item){
// See how much more simple it is to work with classes?
item.classList.toggle("hidden");
});
}
function uploadImage(){
showImage = document.getElementById('put_image_here_bitch').setAttribute('src', input.value);
};
.hidden { display:none; }
<img id="put_image_here_bitch" src="https://cdn0.iconfinder.com/data/icons/finance-vol-2-4/48/77-512.png" alt="" width="100px" height="100px">
<div class="block" > The person who uploads this is cool
</div>
<button>Click to upload photo by URL</button>
<div>
<input id="input" autofocus class='hidden' type="text" id="input">
</div>
<div>
<button class='hidden upload'>UPLOAD</button>
</div>
simple.. getElementsByClassName() returns an HTMLCollection with all DOM elements containing that class. An HTMLCollection is like an array ( but not really ) containing element references.
thus you need to define which entry in the array you want to handle ( even if there's only one )
your code should work by simply adding [0] to your DOM read ( the '0' means the first element in the collection )
ex:
var hide = document.getElementsByClassName('hidden_element')[0];

JQuery: Hide all images except one, starting from the first one and scrolling it

I can't change the HTML code, and it looks like this:
<div class="slider">
<div class="slider-control">
<button id="prev">Previous</button>
<button class="foll">Next</button>
</div>
<div class="slider-image">
<img src="html.png" alt="Html" />
<img src="css.png" alt="Css" />
<img src="jquery.png" alt="jQuery" />
</div>
</div>
When the program starts I need to show the first image. If I click on "Previous" I want to show the previous img (if the currently img showed is the first one, I want to show the last one), if I click on "Next" then I want to show the next img.
I need it to be a generic solution case I need to use it also with more images.
I tried with:
function showImage(){
$(".slider-image img").not(":eq(n)").hide();
}
$(document).ready(function(){
n = 0;
showImage(n);
$(".slider-control button").click(function(){
if($(this).is("div.slider-control.prev")){
n -= 1;
showImage(n);
}
else if($(this).is("div.slider-control.foll")){
n += 1;
showImage(n);
}
});
});
But it doesn't show anything
There was a few issues that I've fixed for you, but this should now work okay for you
showImage was not taking n as a paramater, but you were passing it that when you were calling it
function showImage() {... // Not taking the param you're passing
function showImage(n) {... // Now we are, and assigning it the name 'n'
You weren't using .show() on the element you wanted to show - you were only ever using .hide()
There was also an issue with how spamming the next or previous buttons would change the n higher / lower than your element count, and so you would end up selecting elements that didn't exist. To keep your n within the range of your elements, you can do this to loop back around an array's indexes
n = n % $('.slider-image img').length;
Finally, you weren't passing n to the :not(:eq(n)) - I've just used template literals to insert the variable cleanly
In the HTML, I set your buttons to both use IDs, because I felt this made more sense and helps readabilit
In the $(document).ready(..., you also had an error with your .is() - You were alredy working from the <button> element, so you're okay to check just on the ID of the buttons
function showImage(n){
n = n % $(".slider-image img").length;
$(".slider-image img").not(`:eq(${n})`).hide();
$(".slider-image img").eq(n).show();
}
$(document).ready(function(){
n = 0;
showImage(n);
$(".slider-control button").click(function(){
if($(this).is("#prev")){
n -= 1;
showImage(n);
}
else if($(this).is("#foll")){
n += 1;
showImage(n);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider">
<div class="slider-control">
<button id="prev">Previous</button>
<button id="foll">Next</button>
</div>
<div class="slider-image">
<img src="https://via.placeholder.com/150" alt="Html" />
<img src="https://via.placeholder.com/200" alt="Css" />
<img src="https://via.placeholder.com/250" alt="jQuery" />
</div>
</div>

How to efficiently create 100's of toggle image buttons?

I was looking for a way to change image A to B and B to A by just
clicking them.
So far, this is what I'm using.
<img id="pixelbutton" src="images/pixelbutton.png" />
<img id="pixelbutton2" src="images/pixelbutton_press.png" style="display: none;" />
<script type="text/javascript">
$(document).ready(function(){
$("#pixelbutton").click(function(){
$("#pixelbutton").css({'display':'none'})
$("#pixelbutton2").css({'display':'block'});
})
$("#pixelbutton2").click(function(){
$("#pixelbutton2").css({'display':'none'})
$("#pixelbutton").css({'display':'block'});
})
})
</script>
The script works well for a pair of image.
Now if I have 100 pair of image.
"A <--> B"
"C <--> D"
"E <--> F"
and so on...
Do I have to copy the body HTML and script 100 times and change their ID+URL or there is another more efficient way?
To create hundreds of them... First, use a class.
Then, use a data attribute to store the "alternate" URL.
<img class="pixelbutton" src="images/pixelbutton.png" data-altsrc="images/pixelbutton_press.png"/>
<script type="text/javascript">
$(document).ready(function(){
$(".pixelbutton").click(function(){
// Get the two values
var src = $(this).attr("src");
var altSrc = $(this).data("altsrc");
// Switch them
$(this).attr("src",altSrc).data("altsrc",src);
});
})
</script>
This will work for thousands of .pixelbutton...
;)
EDIT
As per this other .data() documentation, (I wonder why there's two different documentation pages...) the data-* have to be lowercase... Because when trying to get altSrc, it is interpreted as alt-src.
I just learned that... That is quite a strange new standard, from jQuery 3.
So here is your CodePen updated.
You could probably set a naming pattern and use delegation to make an event handler on the images' container.
You could check if the event's target is an image and retrieve its id. Using that id, you could use the pattern you've set to change the images interchangeably.
There are multiple solutions to this, but this is by far the simplest approach:
Wrap your image pairs in a parent <div>
Use .toggleClass() to toggle a class, say .hide, in the images in the element
This solution assumes that you have images in pairs :) see proof-of-concept example:
$(document).ready(function() {
$('img').click(function() {
console.log($(this).siblings());
$(this).add($(this).siblings()).toggleClass('hide');
});
});
/* For layout only */
div {
display: inline-block;
}
/* Used to hide image */
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
Try this one:
jQuery(document).ready(function($) {
var $imgBlock = $('#images');
var html = '';
var imgArr = [
'http://i0.wallpaperscraft.com/image/surface_shape_metal_116716_200x300.jpg',
'http://i0.wallpaperscraft.com/image/universe_space_face_rocket_116714_200x300.jpg',
'http://i0.wallpaperscraft.com/image/letter_surface_wooden_116674_200x300.jpg',
'http://i0.wallpaperscraft.com/image/mountains_lake_reflection_116663_200x300.jpg',
'http://i1.wallpaperscraft.com/image/leaf_drops_surface_116678_200x300.jpg',
'http://i1.wallpaperscraft.com/image/candle_spruce_christmas_decoration_116684_200x300.jpg'
];
$.each(imgArr, function(index, url) {
html += (index % 2 === 0) ? '<div>' : '';
html += '<img src="' + url + '"/>';
html += (index % 2 === 1 || index === imgArr.length - 1) ? '</div>' : '';
});
$imgBlock.append(html);
$imgBlock.on('click', 'img', function(e) {
$(this).parent('div').find('img').removeClass('red');
$(this).addClass('red');
});
});
img {
border: 2px solid #ccc;
}
.red {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="images"></div>

How to get multiple values from HTML using jQuery

I need to get multiple values from my HTML.
<img class="tested" style='display:none' data-src=https://sATES.jpg>
<img class="tested" style='display:none' data-src=https://sATES2.jpg>
<img class="tested" style='display:none' data-src=https://sATES3.jpg>
var elements = $(".tested").data("src");
for (var i = 0; i < elements.length; i++) {
console.log(elements);
}
The problem is that I'm only on getting 1 URL. Any suggestions are most welcome.
There are multiple .tested elements, so you need to loop over each one to get the required data attribute from it. Try this:
$(".tested").each(function() {
console.log($(this).data('src'));
});
var elements = $(".tested");
$(elements).each(function(){
console.log($(this).data("src"));
});
you could use jquery map
var srcs = $('img.tested').map(function() { return $(this).data('src'); });
console.log(srcs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="tested" style="display:none" data-src="https://sATES.jpg">
<img class="tested" style="display:none" data-src="https://sATES2.jpg">
<img class="tested" style="display:none" data-src="https://sATES3.jpg">

html multiselect images

I printed to the screen 16 icons (little pictures).
Now I want to be able to select icons,
and when I press a button the selected icons ids will be sent in a form.
I saw in the net only checkboxes and lists multiselect,
what's the best way to do this?
(I'm pretty new to web design)
thanks ahead!
Although jQuery isn't in your tags, you should introduce yourself to jQuery. It'll make your life easier, for what you're trying to do. Here is the basic steps both if you use jQuery and if use just Javascript:
With jQuery
Give all your icons a class and each one a unique id:
<img src='icon1.png' data-iconID=2233 class='myIcons' />).
Then bind that class to a click event
$('.myIcons').bind('click', function() {
$(this).toggleClass('selectIcon');
});
Attach form submit function to onsubmit:
<form ... onsubmit="submitForm();">
Build submitForm function:
function submitForm() {
var csvIconIds = '';
$.each($('.myIcons.selectIcon'), function (index, value) {
csvIconIds += $(value).attr('data-iconID');
});
//submit scvIconIds here along with other form data (ajax?)
}
With Javascript
Similar as above but way more complicated...
To toggle classes see this thread: How to add/remove a class in JavaScript?
To getting attributes by class see this site: http://www.actiononline.biz/web/code/how-to-getelementsbyclass-in-javascript-the-code/
This could be a way using just plain Javascript or jQuery. I prefer the jQuery version, since it separates the click handler from the markup, instead of using inline onclick handlers, which are in general discouraged.
What this does is use an input element array, which you can create by adding [] to the element name. This same technique can be used on SELECTs and other elements, since it signals to the server that an array has been submitted, as opposed to value known by a single key.
<html>
<head>
<style type="text/css">
div img {
cursor: pointer;
border: 1px solid #f00;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script>
function setFormImage(id) {
if (id != '' && !document.getElementById('input_'+id)) {
var img = document.createElement('input');
img.type = 'text';
img.id = 'input_'+id;
img.name = 'images[]';
img.value = id;
document.imageSubmit.appendChild(img);
}
}
$(document).ready(function(){
$('#jqueryimages img').click(function(){
setFormImage(this.id);
});
});
</script>
</head>
<body>
<pre><?php
if (count($_GET['images'])) {
print_r($_GET['images']);
}
?></pre>
<div style="float: left; width: 49%;">
<h1>Plain ol' HTML</h1>
1. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-1" onclick="setFormImage(this.id)"/>
<br/>
2. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-2" onclick="setFormImage(this.id)"/>
<br/>
3. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-3" onclick="setFormImage(this.id)"/>
<br/>
4. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-4" onclick="setFormImage(this.id)"/>
</div>
<div id="jqueryimages" style="float: left; width: 49%;">
<h1>jQuery</h1>
5. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-5"/>
<br/>
6. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-6"/>
<br/>
7. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-7"/>
<br/>
8. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-8"/>
</div>
<h1>Form Submit</h1>
<form name="imageSubmit" method="get">
<input type="submit" value="View Selected"/>
</form>
</body>
</html>
try this
var idArray = [];
$("#container-id img").each(function(index,value){
idArray.push($(value).attr("id"));
});
//do anything with the array

Categories