Guide to creating a versatile script that adjusts height in JavaScript

If you want to adjust the height of an element using JavaScript, you can do something like this:

function changeHeight(elementId) {
    document.getElementById(elementId).style.height = "200px";
}
<button type="button" onClick="changeHeight('chartdiv');"> Click Me! </button>

However, if you have multiple elements with the same id and buttons assigned to them, clicking on one button will still affect all elements. Is there a way to create a more general method that can be applied to any element?

Answer №1

It is crucial for IDs to be unique. Avoid having multiple elements sharing the same ID.

If you find yourself needing to modify various elements, consider passing arguments to your function:

function adjustSize(selector, size) {
    let item = document.querySelector(selector);
    if (item) {
        item.style.height = size;
    }
}

adjustSize('#chartdiv', '200px');
adjustSize('#otherElement', '500px');

Answer №2

Identification is crucially unique as it serves as the distinct identifier for an element. While multiple elements can bear the same class name, you have to remember this fact:

document.getElementsByClassName("class_name")[0].style.height = "200px";

The usage of document.getElementsByClassName("class_name") fetches an array containing all the elements with that specific class name in chronological order - in other words, to target the first occurrence of that class, you need to refer to the 0th element and so forth.

Remember: It's a cardinal sin to reuse an id. Don't do it!

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

A window interface in Javascript that allows for dynamic arrays and multiple choice answers

I've been working with multiple arrays and encountered a problem. Adding additional questions is not an issue when there's only one question div generated. However, if I add another question div, I can't add more questions to either of the w ...

Retrieve all documents with a matching objectId field in MongoDB

I built an API that can fetch all data from a table, but within this table there is an object ID reference to a user. Table 1 - Story | Table 2 - User api.get('/all_stories', function(req, res) { Story.find({}, function(err, stories) { ...

The issue with triggering button events in JavaScript

I've integrated a jquery modal popup for saving uploaded files related to a specific device. The modal appears, the cancel button functions correctly, but I am struggling to trigger the onclick event for the Save button... This is what I have impleme ...

How to access data from a child component in a Vue 3 template

Within my project, there are three Vue components that utilize the Composite API with the setup option. My goal is to access data within a nested tree structure. The code below provides a simplified version of what I am trying to achieve. The application ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

Developing a interactive quiz platform with JavaScript

I recently attempted to develop a straightforward quiz page using Javascript. Everything seemed to be working fine, until I noticed that when I clicked the submit button in the browser, the text generated in the paragraph section (via Script) vanished almo ...

When the user clicks on the iframe, they will be redirected to the

My goal is to create a scenario where clicking on an iframe opens the same URL in a new browser tab, while ensuring that scroll and other mouse events within the iframe are not affected. I have experimented with various approaches but none have been succe ...

Sending Text Input Data from Angular Form to a Restful API

I'm currently working on a project where I need to send data from a reactive form to a REST API running on my local express.js server. The form consists of basic text input fields like name, surname, and email. When the form data is submitted, it is ...

Can the Flash Configurator be converted to PHP or Javascript?

Considering converting this flash application into either PHP or JavaScript. Take a look at the example: In PHP, the page reloads every time the customer selects a color. With AJAX, it's challenging to pass the selected value to PHP. Are there any ...

Hover over buttons for a Netflix-style effect

https://i.stack.imgur.com/7SxaL.gif Is there a way to create a hover effect similar to the one shown in the gif? Currently, I am able to zoom it on hover but how can I also incorporate buttons and other details when hovering over it? This is what I have ...

Card carousel rotation

Apologies for the vague title, I'm unsure how to properly label my issue. I have a section set up with cards, but I'm aiming to create something resembling a menu that functions like a carousel. Essentially, I want to include right and left arro ...

Learn how to create text animations using CSS triggered by a scroll event listener

I'm looking to create a text animation similar to the one on this website: They have 3 keyframes for two types of animations: Left to Right and Right to Left. The RTL animation starts at 164vh, while LTR starts at -200vh. These text animations only ...

Background image positioned behind a carousel

I'm currently working with a Bootstrap carousel that's functioning perfectly, but I have a desire to incorporate a background image behind this carousel. The background image should be at a width of 100% and 80% of the image should be covered by ...

What steps do I need to follow in order to incorporate the SQLite database into my application?

My attempt to establish a database connection with my system is met with an issue where, upon calling the function, the application's browser displays this message: The "granjas" table is empty Below is the code snippet for reference: In JavaScript ...

Guide to dynamically setting the title and background color of the navigation bar in React Navigation 5

In my current project, I am utilizing React Navigation Bar version 5 and have successfully set the title in App.js. However, I now need to change this title dynamically when the screen is rendered. I attempted to use this.props.navigation.navigate('Ex ...

Tips for getting involved in the Mojito repository on Github for javascript development

Looking for guidance on studying, understanding, and debugging code? I have a good grasp of javascript but unsure where to begin. I am familiar with Github and Mojito, but struggling to contribute to the platform. Any tips on how to get started with Moji ...

Encountering issues with loading Angular formControl

I've been going through an Angular tutorial on forms, which you can check out here. In my 'datasources.component.html' file, I have the following code: <form [formGroup]="queryForm"> <label>Query: <input type="text" formCont ...

Steps to activate highlighting for the initial value in a quarterly datepicker

Concerning the quarterPicker feature in the Bootstrap datePicker (SO: how-to-change-bootstrap-datepicker-month-view-to-display-quarters, jsfiddle: jsFiddle): Is there a way to highlight an initial value upon startup? I have tried setting a value in win ...

Desktop keyboards are essential for inputting data into HTML fields that are not

I'm currently working on developing an on-screen keyboard. My goal is to prevent the mobile device keyboard from opening while the on-screen keyboard is active. One approach is to make the input read-only so that it doesn't open the keyboard when ...

What is the best way to apply a CSS class to a ComponentRef that has been generated in Angular 5

I am attempting to dynamically add a CSS class to a component right after its creation by utilizing ViewContainerRef and ComponentFactoryResolver. My goal is to determine the class based on which other Components have already been added to myViewContainerR ...