HTML DOM getElementsByTagName issue - javascript

Currently, both this is using a button, but is there a possible to have this query without a button but just onclick?
Changes the target of the anchor to google.com:
<button onclick="document.querySelectorAll('ul>li>a').forEach(function(link){link.href='http://google.de';});"> ChangeHREF </button>
Changes the color of the header of the page:
<button onclick='(document.getElementsByTagName("h1")[0]).style.color="blue"'>XSS attach</button>

Add an eventlister for click on a tag e.g. a DIV that starts a function (change). In this function get with querySelector your header H1 and a class blue. Via CSS the color of the header changes to blue.
So you don't need a button for this.
document.getElementById('myDiv').addEventListener('click', change);
function change() {
document.querySelector('h1').classList.add("blue");
}
h1.blue {
background: blue;
}
<h1>Header</h1>
<div id="myDiv">Press this DIV for change H1 to blue</div>

of course you can here is one I used div and you can use other but in the way makes sense like you can't use select
change.onclick = () => {
document.getElementsByTagName('h1')[0].style.color = 'red';
}
<h1>Hello world</h1>
<div id="change">Change Color</div>
change.onclick = () => {
document.querySelectorAll('a').forEach(link => {
link.href = 'http://google.de';
});
var links = document.getElementsByTagName('a');
console.log(links[0].href);
console.log(links[1].href);
}
a
b
<div id="change">Change</div>

Related

How to click on a button and click on it again to close all the content AND how to change image when you go into darkmode using HTML CSS or JS?

(I will link a code sandbox with all my code (at its latest) to be viewed if you want to)
https://codesandbox.io/s/distracted-hellman-pyej06?file=/index.html
I have two issues that I was hoping to address
Problem-1: I have a website called dirieahmed. ml (the same as the code sandbox) I have a night mode / light mode toggle, however when I click on night mode my logo (the image which is called hello.jpg and is above the face picture) will stay the same which makes sense but looks terrible because it looks like an imperfect white square. As a result, I wanted to change this. Therefore when I click on night mode I want the image to change into the night mode version of the logo I have made (it will be called hello-dark.jpg) Is there a way i can do that? I will link the appropriate code down below but if you would like to see the CSS you can view the sandbox
<div class="image1">
<img src="img/hello.jpg" alt="something" width="400" height="300">
</div>
<script async>
<--!This is my dark theme toggle-->
document.querySelector('.theme-toggle-button').addEventListener('click', () => {
document.body.classList.toggle('dark')
})
Problem-2: On my sandbox, you can view an About me, Education and Achievements and Other content elements, these elements are buttons when clicked they will drop down a content, if I click on about me then Education about me will open then close and allow Education to open. Pretty Normal and similarly for the button called "Other" but when i click on Other again to reset all the views and make it clean like when it was originally where no dropdowns exsisted that wont happen. Is there a way for me to make a javascript that will close all content from that div when clicked on it twice. (the code of CSS is in the sandbox but Html and JS will be here)
<div class="container">
<button id="one" class="click one" title="click me">About Me</button>
<div class="list-1 sec">
<h1 class="content-header-one content">Dummy text header</h1>
<p class="content-paragraph-one">Dummy text</p>
</div>
<button class="click two" title="click me">Education and Achivements</button>
<div class="list-2 sec">
<p class="content-paragraph2 content">Dummy text</p>
<ul class="content-list content">
<li>- Achivement #1</li>
<li>- Achivement #2</li>
<li>- Achivement #3</li>
</ul>
</div>
<button class="click three" title="click me" >Other</button>
<div class="list-3 sec">
<h1 class="content-header-two content">Dummy text header</h1>
<p class="content-paragraph3 content">Dummy text</p>
</div>
<script async>
// Instanciate List div's
let list1 = document.querySelector(".list-1");
let list2 = document.querySelector(".list-2");
let list3 = document.querySelector(".list-3");
// Reset's all views to the default without .newlist
const resetAllViews = () => {
list1.classList.remove("newlist");
list2.classList.remove("newlist");
list3.classList.remove("newlist");
};
// Checks to see what button is clicked and shows correct list based on input
document.addEventListener(
"click",
function (e) {
e = e || window.event;
var target = e.target;
if (target.classList.contains("one")) {
resetAllViews();
list1.classList.add("newlist");
}
if (target.classList.contains("two")) {
resetAllViews();
list2.classList.add("newlist");
}
if (target.classList.contains("three")) {
resetAllViews();
list3.classList.add("newlist");
}
}, false);
</script>
</div>
Again you can view the result I have in the sandbox (latest) and on the most recent website dirieahmed.ml for real life view
Sorry if I repeated myself a lot and any help would be appreciated though I prefer if you can show me the code as a runner snippet as I am fairly new so its a bit difficult for me to understand all vocabulary but again any help is appreciated
As for the 1st point, i think you have 2 possibilities:
Add the image as a background image with css, so you can easily toggle. Normally you show the "light" image, and if the body has the dark class then you can show the "dark" image.
The second idea is to add two <img> elements to the page and hide / show accordingly, something like:
.image-light {
display: block;
}
body.dark .image-light {
display: none;
}
.image-dark {
display: none;
}
body.dark .image-dark {
display: block;
}
As to the 2nd point i think you should to it like this:
you have a variable to hold the current open element
when you click a button you get the "value" vor that button
If the value if the same as the current open variable, then you reset the variable (maybe to null), otherwise you set the current open variable to the value of that button
Then you can have an update function. On this function you go through all the of "target" elements. If the element corresponds to the currently open variable, you open it, otherwise you close it.
Something like:
let currentlyOpen = null;
let buttons = document.querySelectorAll(".your-buttons");
let targets = document.querySelectorAll('.your-targets');
button.forEach((button) => {
button.addEventListener('click', (event) => {
const newTarget = event.target.getAttribute('your-identifier-attribute');
currentlyOpen = currentlyOpen === newTarget ? null : newTarget;
updateUI();
});
})
function updateUI() {
targets.forEach((target) => {
targetIdentifier = target.getAttribute('the-identifier-attribute');
targetIdentifier === currentlyOpen
? target.classList.add('your-class-for-open-list')
: target.classList.remove('your-class-for-open-list');
})
}
I have created an example for you:
let openContent = null;
const buttons = document.querySelectorAll('button');
const contents = document.querySelectorAll('.content');
buttons.forEach((button) => {
button.addEventListener('click', (event) => {
const newTargetId = event.target.getAttribute('target-id');
openContent = newTargetId === openContent ? null : newTargetId;
updateUI();
});
});
function updateUI() {
contents.forEach((content) => {
const contentId = content.getAttribute('id');
contentId === openContent
? content.classList.add('visible')
: content.classList.remove('visible');
});
}
.content {
display: none;
}
.content.visible {
display: block;
}
<p> click one of the buttons to show more content</p>
<button target-id="one">One</button>
<button target-id="two">Two</button>
<button target-id="three">three</button>
<p class="content" id="one">Content one</p>
<p class="content" id="two">Content two</p>
<p class="content" id="three">Content three</p>
Here is an example of doing this using two elements where one is hidden based on theme. You could make it a photo that you want to change. This way both images are loaded and you don't have to have the client wait for an image to load when themes change.
The way I accomplished this was mainly in css. The only javascript is to toggle the dark class on the page. The dark page has css variables which represent whether or not elements on the page have a display of none or block. On the actual elements which toggle, I feed those css variables into them. It is also possible to add animations or transitions to make it feel fancy, but hopefully this small demonstration satisfies your need for modifications to your own project.
const $ = str => document.querySelector(str);
const page = $(".page");
$(".theme-toggle").addEventListener("click", () => {
page.classList.toggle("dark");
});
body {
display: grid;
place-items: center;
}
.page {
--light-logo: block;
--dark-logo: none;
display: flex;
flex-direction: column;
text-align: center;
}
.page.dark {
--light-logo: none;
--dark-logo: block;
background-color: black;
color: white;
}
.logo-container {
font-size: 5rem;
}
.logo-container .dark {
display: var(--dark-logo);
}
.logo-container .light {
display: var(--light-logo);
}
<div class="page">
Hello World
<div class="logo-container">
<div class="light">🌞</div>
<div class="dark">🌑</div>
</div>
<button class="theme-toggle">🌞 / 🌑</button>
</div>
Answer 1: It is possible to simple solve by CSS, but this is not good idea for the SEO optimization. Better and most simple solution is to use 2 images and add class "hidden", where you will set for this class {display:none} in css file. Next you must modify your script to set/remove "hidden" class by the selected light/dark mode.
<div class="image1">
<img src="img/hello.jpg" alt="something" width="400" height="300">
</div>
Another better solution is modify the DOM, replace img element when mode is changed, or change the src attribute, e.g.:
document.getElementById("myImageId").src="img/hello-dark.jpg";

Creating a script for a button to close other sections when opening its own sections

This is hard to explain precisely. But here we go:
I have a button that calls a function
<button onclick="myFunction_gsm()">Men</button>
When the button is pressed, it triggers a script. This script grabs a hidden section and displays it. The script goes like this:
<script>
//Gender Selection Script Men//
function myFunction_gsm() {
var x = document.getElementById("men-sizing");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
On the screen this plays out so that you click the button, a section appears, if I click the same button again the section hides again. However, I have another 2 sections. 3 Sections in total. For this example, the above script works for 1 section, the A section. There is also B and C. I would like to include the behavior that when A has been pressed, therefore displaying section A, if I then press the button for B the B section appears but the A section disappears without having to press the A button again. A Dynamic change of sorts.
I am a complete starter for coding but I assume it's something you add into the if statement. Any help would be greatly appreciated.
I would prefer solutions that incorporate the code I have now, since I won't have much use recreating it from scratch. It would solve this, but cause many new problems.
Define a class for all sections, for example sec. On click event pass the selected id, hide all of them and just toggle the selected one.
function myFunction_gsm(sectionId) {
let sec = document.querySelectorAll('.sec');
sec.forEach(itm => {
if(itm.id !== sectionId) itm.style.display = 'none'
})
var x = document.getElementById(sectionId);
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
let sec = document.querySelectorAll('.sec');
sec.forEach(itm => {
itm.style.display = 'none'
})
<button onclick="myFunction_gsm('sec1')">Sec1</button>
<button onclick="myFunction_gsm('sec2')">Sec2</button>
<button onclick="myFunction_gsm('sec3')">Sec3</button>
<div class="sec" id="sec1"> some text 1 here</div>
<div class="sec" id="sec2"> some text 2 here</div>
<div class="sec" id="sec3"> some text 3 here</div>
You might use class names for the sections. Then at the start of the function have all elements with that class name be hidden and afterwards display the currently clicked one.
If you want to preserve the toggle functionality for the section (so clicking A twice displays and hides it again), you want to check the display state of the currently clicked one first before hiding all. And then only display the clicked one if it was hidden before.
The modern approach is to avoid using .style within JS. This add the stylign as inline-style which ahs the highest specificty weight with exeption of important. The modern solution is to use classList to apply, remove or toggle a CSS-Class.
You add a class to CSS to hide element such as: .display-none { display: none; }`
Then you add a function to your button to hide all sections with a certain class by adding the class mentioned at step 1: function hideAll() { document.querySelectorAll('.class-name').forEach(el => el.classList.add('display-none')); }
You add a second function to the onclick trigger of a button thow a certain element by removing the class: element.classList.remove('display-none');
function hideAll() {
document.querySelectorAll('.section').forEach(el => el.classList.add('display-none'));
}
function showA() {
document.querySelector('#section-a').classList.remove('display-none');
}
function showB() {
document.querySelector('#section-b').classList.remove('display-none');
}
function showC() {
document.querySelector('#section-c').classList.remove('display-none');
}
.display-none {
display: none;
}
<button onclick="hideAll(); showA()">Show A</button>
<button onclick="hideAll(); showB()">Show B</button>
<button onclick="hideAll(); showC()">Show C</button>
<section id="section-a" class="section display-none">Section A</section>
<section id="section-b" class="section display-none">Section B</section>
<section id="section-c" class="section display-none">Section C</section>
CSS-only Solution
If you dont want to sue scripts, you could use a pure CSS-Method that works through the :target selector. This allows you to use anchor as "trigger".
Hide the scetiond with display: none; either by selecting them directly or adding a class to them.
use an anchor with an href="#id" instead of a link. This will move the page to that element but also manipulate the websites adress.
Use *:target { display: block; } to show targeted elements:
.display-none {
display: none;
}
*:target {
display: block;
}
/* for styling purpose only */
a {
margin-right: 15px;
}
Show A
Show B
Show C
<section id="section-a" class="display-none">Section A</section>
<section id="section-b" class="display-none">Section B</section>
<section id="section-c" class="display-none">Section C</section>

How to delete HTML section using a function of js?

I need to remove a HTML section using a button. The button is in the HTML section I want to remove. And the section I want to remove was previously added by a button.
With Add section button I add a section below the first section, but I can't create a function to remove a section, I can't select the section I want to remove.
image of web
You're able to use the remove() method in order to do that.
Example:
HTML:
<div id="testID">your stuff.</div>
<button onclick="deleteDiv()">Delete</button>
JS:
function deleteDiv() {
var selectedDiv = document.getElementById("testID");
selectedDiv.remove();
}
try this code:-
<p id ="remove" style = "color: green; font-size: 24px; font-weight: bold;">
on click remove this section
</p>
<button onClick = "remove()">
click here
</button>
var htmlElement = document.getElementById('remove'); //use getElemeyId or getElementsByClassName According to your need;
function remove() {
htmlElement.remove();
}

changing the background color on clicking on the button

I'm learning javascript!
What I need to do, is to change the background-color at the same time when the image is changing by clicking on the button.
Changing the picture, from light-On to light-off, is working properly, the only problem is that the color of the background of my html page, is not changing.
function colorize() {
var element = document.getElementById("azul");
element.style.backgroundColor = 'blue';
element.style.color = "yellow";
}
html{
background:
grey;
}
#azul:focus {
background: blue;
}
<div id="branca">
<h1>LOI Lampen aanzetten en uitzetten</h1>
<button id="azul" onclick="document.getElementById('myImage').src = '/img/393533_02.PNG'">Turn on the light</button>
<img id="myImage" src="img/393533_01.PNG" class="mudar">
<div id="yellow">
<button onclick="document.getElementById('myImage', '').src='/img/393533_01.PNG'">Turn off the light</button>
</div>
</div>
You want to change background of html so what you have to do is...
function colorize() {
var element = document.getElementsByTagName("html")[0];
element.style.backgroundColor = 'blue';
}
You were taking button element and changing its color. you have to select html tag as you want to change the background-clor property assigned to it via css.
This is your solution call the colorize function too
<html>
<script>
function colorize() {
var element = document.getElementsByTagName("html")[0];
element.style.backgroundColor = 'blue';
element.style.color = "yellow";
}
</script>
<style>
html{
background:
grey;
}
#azul:focus {
background: blue;
}
</style>
<div id="branca">
<h1>LOI Lampen aanzetten en uitzetten</h1>
<button id="azul" onclick="document.getElementById('myImage').src = '/img/393533_02.PNG';colorize()">Turn on the light</button>
<img id="myImage" src="img/393533_01.PNG" class="mudar">
<div id="yellow">
<button onclick="document.getElementById('myImage', '').src='/img/393533_01.PNG'">Turn off the light</button>
</div>
</div>
</html>
You need to change the background color of the document, not element, which is your button.
Since you are new to JavaScript, let's get you off of some bad habits that you've already picked up.
Do not set up event handlers via HTML event attributes (i.e. onclick, onmouseover, etc.). This is a 25+ year old technique that we used before we had modern standards and best practices and because it's easy to use, people keep using it. But there are a variety of reasons why you should not use this technique and instead separate your JavaScript from your HTML. Instead, keep your JavaScript separate and use .addEventListener() to hook up your elements to their respective callback functions.
Whenever possible, work with pre-made CSS classes because these are easier to manage and reuse than inline CSS styles (via the .style property). You can then easily use the element.classList API to add or remove classes as needed.
See the comments inline below:
// Get references to the elements you'll need to work with
let targetImage = document.getElementById('myImage');
let btnOn = document.getElementById("on");
let btnOff = document.getElementById("off");
// Then, set up your event handlers in JavaScript, not HTML
btnOn.addEventListener("click", changeImage);
btnOff.addEventListener("click", changeImage);
function changeImage(){
// Set the target's source to the data-source attribute for the clicked button
targetImage.src = this.dataset.source;
targetImage.alt = this.dataset.alt // Now update the alt attribute
// Change the background color of the page by adding or removing a
// pre-made class to/from the body based on the button that was clicked
// Since this is a simple if/then scenario, we can use the JavaScript "ternary" operator
// which works like this: some condition ? what to do if condition is true : what to do if false
this.id === "on" ? document.body.classList.add("blue") : document.body.classList.remove("blue");
}
body { background-color: grey; } /* Style the body, not the HTML */
#on:focus { background: blue; color:yellow; }
.blue { background-color:aliceblue; } /* This will be added when on is clicked */
/* Just for this example only */
img { width:100px; }
<button id="on" data-source='https://cdn.wccftech.com/wp-content/uploads/2015/04/bulb_PNG1250.png' data-alt="On Image">Turn on the light</button>
<button id="off" data-source='https://www.radioducoeur.com/liten/radioducoeur/light-bulb-png-home-design-ideas-4-lightbulb-498-x-498-liten.jpg' data-alt="Off Image">Turn off the light</button>
<div>
<!-- <img> elements must have an alt attribute to be valid -->
<img id="myImage" src="https://www.radioducoeur.com/liten/radioducoeur/light-bulb-png-home-design-ideas-4-lightbulb-498-x-498-liten.jpg" class="mudar" alt="default image">
</div>
Here is your code:
<style>
body {
background: grey;
}
</style>
<script>
function colorize(light) {
if (light) {
document.getElementById('myImage').src = '/img/393533_02.PNG';
document.body.style.background = 'grey';
}
else {
document.getElementById('myImage').src = '/img/393533_01.PNG'
document.body.style.background = 'blue';
}
}
</script>
<body>
<div id="branca">
<h1>LOI Lampen aanzetten en uitzetten</h1>
<button id="azul" onclick="colorize(true)">Turn on the light</button>
<img id="myImage" src="img/393533_01.PNG" class="mudar"/>
<div id="yellow">
<button onclick="colorize(false)">Turn off the light</button>
</div>
</div>
</body>
Now in colorize function you can write as much parameters as you want for two different conditions.

How can I conditionally change css styles with js?

I'd like to implement some javascript that uses an if statement to change some css styles. Not sure how to do it, any help would be great!
If you want to change a single style of an element using JavaScript, use
document.getElementById(id).style.property = new style
eg :
document.getElementById("myDiv").style.color= "red";
To add a new CSS class to an element, use
document.getElementById(id).classList.add("mystyle");
To remove
document.getElementById(id).classList.remove("mystyle");
Demo :
function changeSingleStyle() {
var color = document.getElementById("myDiv").style.color;
if (color === "red")
document.getElementById("myDiv").style.color = "yellow";
else
document.getElementById("myDiv").style.color = "red";
}
function addClass() {
document.getElementById("myDiv").classList.add("mystyle");
}
function removeClass() {
document.getElementById("myDiv").classList.remove("mystyle");
}
.mystyle {
color : red;
background: green;
font-size: 50px;
}
<div id="myDiv"> This is a div </div>
<button onclick="changeSingleStyle()">changeSingleStyle</button>
<button onclick="addClass()">addClass</button>
<button onclick="removeClass()">removeClass</button>
First of all, to change CSS using JavaScript, the syntax looks like the following:
document.getElementById(id).style.property = new style
For example, if you want to change the display property of an element with id = "container" to block, it would be:
document.getElementById("container").style.display = "block";
Given this, you could easily add an IF statement depending on what condition you want. For example:
if(condition)
{
document.getElementById("container").style.display = "block";
}
You can do this with .style.property or .style.cssText
function myStyleFunction() {
document.getElementById('styled').style.color = 'red';
}
function myStyleFunctionCssText() {
document.getElementById('styled2').style.cssText = 'color: lime';
}
<button onclick="myStyleFunction();" id="styled">
Style with .style.color
</button>
<button onclick="myStyleFunctionCssText();" id="styled2">
Style with .style.cssText
</button>
With this code, the button on the left will go red, the one on the right will go lime.
You can also do this easily with jQuery.
function myStyleFunction() {
$(".style").css("color", "magenta");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="style" onclick="myStyleFunction();">Style by class</button>
<button class="style">Style by class 2</button>
This code changes all elements in the classes color to magenta if you click the first button.
function barHtml (percent) {
return `
<div class= "${percent>25 ? "class1":" class2"}"
style="width: ${percent}%;">
</div>`
}
document.body.innerHTML=<div>${barHtml(20)}</div>

Categories

Resources