Different ways to manipulate the CSS display property with JavaScript

Having trouble changing the CSS display property to "none" using JavaScript.

Check out my code:

<div class="mydiv" onClick="clickDiv1()">hello</div>
<div class="mydiv" onClick="clickDiv2()">hi</div>
<div class="mydiv" onClick="clickDiv3()">goodbye</div>

And here's my script:

 function clickDiv1() { 
alert('You clicked the first div!');
document.getElementByClassName('mydiv').style.display="none";
}

 function clickDiv2() {
alert('You clicked the second div!');
document.getElementByClassName('mydiv').style.display="none";
}

 function clickDiv3() {
alert('You clicked the third div!');
document.getElementByClassName('mydiv').style.display="none";
}

I want each div to show a different alert text when clicked, but all divs become invisible when any of them is clicked on.

The alerts work, but the style doesn't change as expected when I click on a div. Any ideas why it's not working?

Please assist me with this issue! Thank you!

Answer №1

The distinction arises when utilizing class to select elements with

document.getElementByClassName('mydiv')
, as it returns an array of items. Therefore, you must specify which item in the array by using
document.getElementByClassName('mydiv')[i]
, where i represents the array index. Conversely, document.getElementById('div3') will only retrieve a single element.

document.getElementByClassName('mydiv')[0].style.display="none";

or

document.getElementById('div3').style.display="none"; 

should do the trick.

Answer №2

The best way to target HTML elements using Javascript is by utilizing the getElementsByClassName() method.

When you call this method, it will retrieve an array of all elements on the page that have the specified class name. You can then iterate through each element in the array and individually hide them by setting their display property to none.

If we apply this concept to a practical example:

function hideAll() {
  var elements = document.getElementsByClassName('mydiv');
  for (let i = 0; i < elements.length; i++) {
    let element = elements[i];
    element.style.display = 'none';
  }
}

function clickDiv1() {
  alert('You clicked the first div!');
  hideAll();
}

function clickDiv2() {
  alert('You clicked the second div!');
  hideAll();
}

function clickDiv3() {
  alert('You clicked the third div!');
  hideAll();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An effective method to showcase the HTML content retrieved by getElementsByClassName using JSON.parse()

Can someone help me modify this code so that it displays the value of favFood? It currently works with getElementById but not getElementsByClassName, and I want to use a class: server file - ProcesssingFileOnServer.php: <?php $myObj = new stdClass(); ...

Click the button to access the login form created using React components

I have been working on developing a login form that includes various input components and a button component. SignIn.js class SignIn extends Component { render() { return ( <article className="br2 ba dark-gray b--black-10 mv4 w-100 w-50-m ...

I have successfully implemented the Context API in my Next.js project and everything is functioning smoothly. However, I encountered an error while using TypeScript

Currently, I am working on a Next.js project that involves using the Context API. The data fetched from the Context API works perfectly fine, but I am encountering errors with TypeScript and I'm not sure how to resolve them. Error: Property openDialo ...

How can I stop columned-DIVs from wrapping on the webpage?

I am attempting to create floating/stacking boxes on the right side of the page as long as there is available space. I am close to achieving my desired layout, but the DIVs keep getting wrapped over each other, causing the headings to be lost. ...

Modify the appearance of a nested div using CSS hover on the main JSX container

Within the material-ui table component, I am dynamically mapping rows and columns. The className is set to clickableRow. The TableRow also includes a hover options div on the right side: const generateTableHoverOptions = () => { if (selected) { ...

The replaceWith() function in jQuery is able to transform PHP code into an HTML comment

How can I change a div element in a click event handler, while ensuring that PHP code inside the element remains intact and does not get moved into an HTML comment? You can find my code snippet below: $("#replaceCat1").click(function(){ $("div.boxconte ...

Is there someone who can assist me in transferring data from an Axios JSON response to plot points on a line chart using Chart js?

I'm currently in the process of developing a React application that includes a line chart showcasing the timeline of data recordings starting from a specific point in time up to the present day. To achieve this, I am leveraging the Chart.js JavaScript ...

How do I modify the sidebar width with CSS code?

I am trying to adjust the width of the right sidebar on my website. The current layout leaves too much empty space on the right side and makes it appear crowded next to the main content and images in the center. Despite exploring various solutions provide ...

Tips for showing a map in a concealed location: Embed the code in the appropriate location

I've come across solutions for displaying a map in a hidden div, but as a designer and not a programmer, I'm unsure of where to insert the code. The issue is detailed in this post: Click here to view. To resolve the problem, the suggestion is to ...

Choose an input element from an iframe using jQuery

Can anyone assist me with selecting an input field from an iframe using jQuery? The structure of the iframe is as follows: <iframe src="https://checkout.klarna.com" id="klarna-checkout-iframe" name="klarna-checkout-iframe" class="kloading" scrolling="n ...

What is the best way to incorporate the :after pseudo-element in JavaScript code

HTML: This is my current code snippet <div class="one"> Apple </div> I am looking to dynamically add the word "juice" using JavaScript with the .style property. Is there an equivalent of :: after in CSS, where I can set the content in JavaS ...

Maintaining DOM modifications once a link has been clicked and the Back button is pressed

Is there a way in JavaScript to prevent appended items from disappearing when the user clicks another link and then presses the Back button after using jQuery's appendTo() method to add items to an unordered list? ...

Utilizing props to transfer data between components in ReactJS

I have a React application where I am binding text values when a specific div is clicked. However, I am now faced with the challenge of passing these text values to another component using props. This is what my code looks like: class PostOptionBar exten ...

An effective method for targeting a specific button within a CSS file

I have multiple button tags in my code, but I need to style a specific one using CSS. How can I target this particular button and apply styles only to it while leaving the others unchanged? Do I need to assign the button to a variable and reference that va ...

The SQLite database accessed through Flask exclusively returns variables, rather than actual data

I have a custom flask application that interacts with a sqlite database: @app.route('/<subject_id>') def subject_id_lookup(subject_id): entries = query_db('select visitdt, cvnotes from exam where id = ?', ...

Troubleshooting CSS navigation bar hamburger dilemma

Currently, I am facing an issue with a toggle button on my website. When I click on the hamburger menu, the navigation bar does not show up even though the toggle feature is working perfectly fine. I have tried combining different sources to solve this pro ...

Getting YQL financial information using jQuery and showing it using the .html() method

Struggling with the .html() function and YQL data pulled issue. Despite data being pulled successfully (as seen in the YQL console), it is not being displayed. Here's the provided code snippet: HTML Section <ul id="TECO-container"> <li ...

Creating a Flot Bar Chart that displays non-stacking values

I am new to using Flot for creating charts. Currently, I have a bar chart displayed below: https://i.stack.imgur.com/RSumf.png Here is the code snippet I utilized to generate this chart: $.getJSON('chartBar.json', function(graphDataBar){ $ ...

w3schools example showcasing the power of AJAX

How can I run this example on my local machine? http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_httprequest_js (page no longer available) I want to access the XML file hosted on w3schools without moving it to my machine. Can I run the HTML and J ...

Managing the height of a TextArea within a Flexbox environment

After exploring various methods for achieving auto-height in a textarea, I decided to go with the contenteditable approach as it seemed cleaner to me. However, while it worked perfectly on its own, it failed when placed within flexbox containers. I experi ...