Simplify code by applying property to multiple variables at once - javascript

I want to simplify this code
let a = document.querySelector(".arrow");
b = document.querySelector(".demo-desc1");
c = document.querySelector(".demo-title h3");
a.style.display = "none";
b.style.display = "none";
c.style.display = "none";
so I don't have to write style.display = "none" for every variable but rather to apply the propery for all variables at once.
Thank you.

If there's only one element of each in the DOM, put them all into a selector string, then iterate over the matching elements.
for (const elm of document.querySelectorAll('.arrow, .demo-desc1, .demo-title h3')) {
elm.style.display = 'none';
}
If there are multiple such elements, then you'll need
const selectors = ['.arrow', '.demo-desc1', '.demo-title h3'];
for (const s of selectors) {
document.querySelector(s).style.display = 'none';
}
But, in this sort of situation, an even better approach would be to toggle a class of a parent container, and have CSS rules that hide those elements when the class is on the parent container. I don't know what the rest of your HTML is like, but perhaps something like
<div class="demo-container">
<more HTML here>
</div>
.hide-children .arrow, .hide-children .demo-desc1, .hide-children .demo-title h3 {
display: none;
}
Then all you need is
document.querySelector('.demo-container').classList.add('hide-children');

Related

How do I toggle DOM elements to show and hide

On my index.JS file, I created elements using documentCreateElement and appended them to the DOM to show data from an api. Then I created an event listener which works where if I click my H3 element, it will show my H4 and P element. But I want it to where if I click my H3 element again, I want the H4 and P elements to hide. This is the code I have for my click event listener:
`H3.addEventListener(‘click’, clickFunction)
Function clickFunction() {
Div.append(h4)
Div.append(p)
}`
Can someone please help me?
I tried to look up toggling functions online or incorporate CSS hidden class to the h4 and p elements but nothing was hiding
Try modifying your clickFunction() to check if the elements are already displayed or not.
let isDisplayed = false;
function clickFunction() {
if (isDisplayed) {
// If the elements are already displayed, hide them
h4.style.display = "none";
p.style.display = "none";
isDisplayed = false;
} else {
// If the elements are not displayed, show them
div.appendChild(h4);
div.appendChild(p);
isDisplayed = true;
}
}
h3.addEventListener("click", clickFunction);
In above example, its a boolean variable isDisplayed to keep track of whether the elements are currently displayed or not. When the h3 element is clicked, the clickFunction() is called, and it checks the value of isDisplayed. If its true, it means the elements are already displayed, so we hide them by setting their display style to "none" and setting isDisplayed to false. If it's false, it means the elements are not displayed, so we show them by appending them to the div and setting isDisplayed to true.
Note that you'll need to deeclare the isDisplayed variable outside of the clickFunction() so that its value is preserved between function calls. And make sure to select the h4, p, and div elements using document.querySelector() or a smilar method before using them in the function.
You can try this in your clickFunction
Function clickFunction() {
if(!Div.hasChildNodes()) {
Div.append(h4)
Div.append(p)
} else {
Div.removeChild(Div.childNodes(0))
Div.removeChild(Div.childNodes(1))
}
}
Check this for more info.
Follow the below steps-
Find the existing p and h4 elements.
If found then remove those using the removeChild method, else append those using the append method.
Here is a working demo of toggling the elements-
let h3 = document.querySelector('h3');
h3.addEventListener('click', clickFunction)
let div = document.querySelector('div');
function clickFunction() {
// Find already exists p and h4 elements
let p_exists = document.querySelector('p');
let h4_exists = document.querySelector('h4');
// If found then remove one by one
if (p_exists && h4_exists) {
div.removeChild(h4_exists);
div.removeChild(p_exists);
}
// Else, create and append
else {
let h4 = document.createElement('h4')
h4.innerText = "I am a h4 element";
let p = document.createElement('p')
p.innerText = "I am a p element";
div.append(h4, p);
}
}
<h3>Click</h3>
<div></div>
Using a CSS style rule and checking for the existence of the CSS style rule class name on each HTML element's class list is a common method for toggling the display state of an element.
I used a hide class name in the code snippet but you can change to a 'show' class name with some minor modifications to the code and CSS rules.
var H3 = document.getElementById("h3-elem");
H3.addEventListener("click", clickFunction);
var Div = document.getElementById("div-elem");
function clickFunction() {
var h4 = document.getElementById("h4-elem");
var p = document.getElementById("p-elem");
if (!h4) {
h4 = appendH4();
}
if (!p) {
p = appendP();
}
// Option 1:
// Use the built-in 'toggle()' method on the class list
// for each element.
// https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle
// h4.classList.toggle("hide");
// p.classList.toggle("hide");
// Option 2:
// Check if the class list for the 'h4' and 'p' elements
// contain 'hide' class name. If the class list does not
// contain the class name then add the 'hide' class name
// to the class list.
if (h4.classList.contains("hide")) {
h4.classList.remove("hide");
} else {
h4.classList.add("hide");
}
if (p.classList.contains("hide")) {
p.classList.remove("hide");
} else {
p.classList.add("hide");
}
}
// Set to hide initially. After creation of the element,
// the 'clickFunction' will determine the display state
// of the element by checking for the existense of the
// 'hide' class name.
function appendH4() {
var h4 = document.createElement("h4");
h4.id = "h4-elem";
h4.className = "hide";
h4.textContent = "Header 4";
Div.append(h4);
return h4;
}
function appendP() {
var p = document.createElement("p");
p.id = "p-elem";
p.className = "hide";
p.textContent = "A paragraph";
Div.append(p);
return p;
}
.hide {
display: none;
}
<h3 id="h3-elem">Header 3</h3>
<div id="div-elem"></div>

Toggle Hiding/Showing an Element

I'm trying to have a couple of buttons to show and hide some pictures, I have gotten it to somewhat work, but when I start the webpage the pictures are already shown, when I try make them invisible at start. I have tried swapping the "block" and "none" sentences in the function, but it just made the button less responsive.
javascript part:
function bassnectar() {
var x = document.getElementById("myDIV3");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
html part:
<button onclick="bassnectar()">Bassnectar</button>
<div id="myDIV3">
<img src="/images/bassnectar.jpg">
</div>
What you’re missing is that you’re assuming that block elements have a default display value of block. Which would be intuitive.
Such is not the case though.
The initial value of display is the browser’s default. If you query the value of the display property on a new HTML element, you’ll get an empty string.
It doesn’t return block until you explicitly set its display to block.
Edit:
It's important to note that setting a value in CSS doesn't change the behavior. If you set a div to be display block in CSS, it will still return an empty string if you query it.
Here's a working example:
var block = document.createElement("div");
var inline = document.createElement("span");
console.log("Initial display values:")
console.log(`block.style.display: ${block.style.display}`);
console.log(`inline.style.display: ${inline.style.display}`);
block.style.display = "block";
inline.style.display = "inline";
console.log("\nAfter setting them explicitly:")
console.log(`block.style.display: ${block.style.display}`);
console.log(`inline.style.display: ${inline.style.display}`);
div {
display: block !important;
}

How to select an element with specific css value in javascript

I want to select an element if it has a css as display block then do this function. If the element has the css as display block then remove ('hide') class from the header class.. This is what I want to do.. Any help?
Well, there are two solutions depending on what you want:
Solution 1
Looping through all elements and removing hide class from the current element if it has display block value in its style.
var elements = document.getElementsByTagName("*");
for(let i = 0; i < elements.length; i++) {
if(elements[i].style.display == "block") {
elements[i].classList.remove("hide");
}
}
Solution 2
Getting the reference of the element via HTML id.
var element = document.getElementById("YourElementID");
if(element.style.display == "block") {
element.classList.remove("hide");
}
You can define an id like this in your HTML file:
<div id="YourElementID">Div</div>
I am assuming that you want to determine if the element has the "hide" class by checking its display style. you don't need to do that, you can easily check its class list by using the following code:
element.classList.contains("hide");
There are several ways of collecting all the elements with display: block and i am not sure, which one performs best - or whether it performs good at all.
If you want all the Element instances of the page, which have a computed style of display: block you can do something like:
var $els = Array.from(document.body.querySelectorAll('*')).filter(function($el) {
return getComputedStyle($el).display === 'block';
});
Or ES6:
const $els = Array.from(document.body.querySelectorAll('*')).filter($el => getComputedStyle($el).display === 'block');
If you want the Element instances which have display: block literally set in the style-attribute, you have to do something like this:
var $els = Array.from(document.body.querySelectorAll('*')).filter(function($el) {
return $el.style.display === 'block';
});
I think it would perform better, if the selector in querySelectorAll() would be a little more specific.
Another option would be to use the TreeWalker API, but then you have to do a mutation, because you have to iterate over all the elements and push them to an array:
var $els = [];
walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
while (walker.nextNode()) {
if (getComputedStyle(walker.currentNode).display === 'block') {
$els.push(walker.currentNode);
}
}
Once you have all your elements, you can do something with them.
A little bit more information would be helpful, especially what exactly you want to achieve, once you have the elements, because then i could also provide more help. Maybe provide a code example?

How to show a display:none DIV using Javascript

I have a DIV which has a display set to none, by using javascript I tried showing it by using the onclick of a button. But what happens is the exact opposite. My DIV is already shown and when I click the button it hides the DIV. What am i doing wrong here, please HELP!
This is my button and the div:
<button onclick="myFunction()">SHOW</button>
<div id="how_to_form">
<img src="../images/view.png">
</div>
This is the JS code:
function myFunction() {
var x = document.getElementById("how_to_form").style.display = 'none';
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
Your line there has a double assignment:
var x = document.getElementById("how_to_form").style.display = 'none';
It first assigns the display to none:
document.getElementById("how_to_form").style.display = 'none';
and then takes the result of that expression (which is the string you assigned), and assigns it to x:
var x = 'none';
Which isn't what you want. First declare the variable for the element, then assign its style.
Also, it sounds like you want the element to start out hidden - assign its initial style outside the function:
const form = document.getElementById("how_to_form");
form.style.display = 'none';
function myFunction() {
if (form.style.display === "none") {
form.style.display = "block";
} else {
form.style.display = "none";
}
}
Or, to be more concise, use the conditional operator:
function myFunction() {
form.style.display = form.style.display === "none"
? 'block'
: 'none';
}
Also consider attaching the handler properly using Javascript, rather than using inline HTML attributes, which are generally considered to be pretty poor practice and can be hard to manage:
document.querySelector('button').addEventListener('click', myFunction);
have you checked if you have already set a default style to your div?
you either have to set your div's default style to display:none by inline
<div id="how_to_form" style="display:none">
or by css
<style>
#how_to_form{ display:none }
</style>
Issue is your variable assignment
Chaining the assignment operator is possible in order to assign a single value to multiple variables.
Please refer this link for variable assignment options
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators
var x = y= 10
Then both x and y values are 10
Similarly in your code var x is none
To achieve expected result , use below option
1. set CSS for html_to_form to display:none
2.In your code change variable x assignment to
var x = document.getElementById("html_to_form")

Javascript - get class of another element with onclick

I want to individually toggle to different divs using the same function. Each of these divs has a common class and a different id. The function toggle is called using an onclick parameter on two separate <a> elements:
<a class="btn" id="btnOne" onclick="toggler();">Show/hide divOne</a>
<div class="box" id="divOne">
<a class="btn" id="btnTwo" onclick="toggler();">Show/hide divTwo</a>
<div class="box" id="divTwo">
I first tried to get these divs with getElementsByClassName but, as it returns an HTMLCollection, the script can't target each div individually.
So I tried to select the <a> tags ids (btnOne and btnTwo), but couldn't figure out how to retrieve the divs class using these ids (as we're talking about two different elements here).
In the end, I came back to the getElementById method, as I couldn't figure out how to select them based on their class:
function toggler() {
var id = document.getElementById("divId");
if (id.style.display === "none") {
id.style.display = "block";
} else {
id.style.display = "none";
}
};
This leaves me with two functions instead of just one. Any suggestion on how to target the two divs individually?
You can access the next sibling using nextElementSibling presuming the box will always be right after the hyperlink.
// Put the buttons into an array
const buttons = [...document.getElementsByClassName("btn")];
// Assing an event listener for every button
buttons.map(button => button.addEventListener("click", function(e) {
// Find the next sibling
const box = e.target.nextElementSibling;
// Toggle the display value
if (box.style.display === "none") {
box.style.display = "block";
} else {
box.style.display = "none";
}
}));
a {
display: block;
}
.box {
width: 5rem;
height: 2rem;
background-color: blue;
}
<a class="btn">Show/hide divOne</a>
<div class="box"></div>
<a class="btn">Show/hide divTwo</a>
<div class="box"></div>
There is a simple way to select the divs with their class name and you already used it.
The answer is getElementsByClassName. But in vanilla JS things are a little bit (over)complicated.
It will not target both divs individually. Instead, if you want to select the first div with this class you would do it like this:
getElementsByClassName('classname')[0]
If you want to select the second div you would use:
getElementsByClassName('classname')[1]
and so on. But there is a way of course.
You want to use loops:
var x = document.getElementsByClassName("classname");
for (var i = 0; i < x.length; i++) {
if (x[i].style.display === "none") {
x[i].style.display = "block";
} else {
x[i].style.display = "none";
}
}
In this way, you will target ALL divs with this class.
I'd dynamically add the events on the switches, using their classes. I added the class showHideDivBtn to them. To make sure you know which div you have to toggle, I used a data-id.
With addEventListener, I can use the event variable I named e. With this one, I have access to properties, such as the data-id I wrote.
let buttons = document.getElementsByClassName("showHideDivBtn");
for (let i = 0; i < buttons.length; ++i)
{
buttons[i].addEventListener('click', function(e)
{
let divToToggle = document.getElementById(e.srcElement.dataset.id);
if (divToToggle.style.display === "none")
divToToggle.style.display = "block";
else
divToToggle.style.display = "none";
});
}
<a class="btn showHideDivBtn" data-id="divOne" id="btnOne">Show/hide divOne</a>
<div class="box" id="divOne">One</div>
<br />
<a class="btn showHideDivBtn" data-id="divTwo" id="btnTwo">Show/hide divTwo</a>
<div class="box" id="divTwo">Two</div>
Use substr to get the word after extracting 'btn' from anchor id which will result in One or Two then while defining the if use "div"+word this will get the div by it is related a tag
function toggler() {
var word=this.id.substr(3);
var id = document.getElementById("div"+word);
if (id.style.display === "none") {
id.style.display = "block";
} else {
id.style.display = "none";
}
};

Categories

Resources