What is the correct way to set up getElementById?

Having some trouble with the getElementById() function not functioning as expected and unable to identify the issue.

This is an excerpt of my HTML body:

<button type="button" id="up">Increase Volume</button>
<button type="button" id="down">Decrease Volume</button>
<script src="final.js"></script>

Contained within my script file is the following code snippet:

const upButton = document.getElementById("up");
const downButton = document.getElementById("up");


initialize();

function initialize(){

    upButton.setAttribute("width", "300px");
    console.log(upButton.getAttribute("width"));
    upButton.setAttribute("left", (Math.floor(Math.random() * 1000)).toString() + "px");

    downButton.setAttribute("top", (Math.floor(Math.random() * 1000)).toString() + "px");
    downButton.setAttribute("left", (Math.floor(Math.random() * 1000)).toString() + "px");
}

Answer №1

Attempting to use setAttribute for a different purpose.

For instance, when executing

upButton.setAttribute("width", "300px");
, it essentially transforms into:
<button type="button" class="button" id="up" width="300px" left="359px" style="width: 300px;">Increase Volume</button>

This discrepancy is noticeable by inspecting the element. The method can only work if the button actually employs such attributes.

Resource reference: https://www.w3schools.com/jsref/met_element_setattribute.asp

To accomplish your objective, as suggested in a prior comment, you should manipulate the style object:

const upButton = document.getElementById("up");
const downButton = document.getElementById("down");

function initialize(){
  upButton.style.width = '300px'
  upButton.style.left = (Math.floor(Math.random() * 1000)).toString() + "px"

  downButton.style.top = (Math.floor(Math.random() * 1000)).toString() + "px"
  downButton.style.left = (Math.floor(Math.random() * 1000)).toString() + "px"
}

initialize();
.button {
  position: absolute;
}
<button type="button" onclick="initialize()">Change position</button>

<button type="button" class="button" id="up">Increase Volume</button>
<button type="button" class="button" id="down">Decrease Volume</button>

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

Effectively handling server downtime with AngularJS $resource

I've implemented this code in my services.js file: angular.module('appServices', ['ngResource']). factory('User',function ($resource) { return $resource('http://localhost\\:3001/api/user/:id', { ...

Issue with rendering components list in React.js

I am currently working on a project using React, and I'm facing an issue where my list is not displaying on render(). In my parent component, I have a list of components coming from SearchResult. Below is the relevant portion of my code: class Create ...

Middleware running twice

I developed a custom Middleware to handle my page requests, but I'm facing an issue where it seems to be running twice... The first run goes smoothly without any errors, but the second time around, I encounter errors... Here is the code snippet: ap ...

React HTML ignore line break variable is a feature that allows developers to

Can you help me with adding a line break between two variables that will be displayed properly in my HTML output? I'm trying to create an object with a single description attribute using two text variables, and I need them to be separated by a line b ...

Is there a way to dynamically change the helperText of a Material UI TextField using its current value through code?

I'm currently attempting to dynamically change the helperText of a Material UI TextField based on the value entered into the field. Below is my current implementation: const defaultScores = { STR: 10, DEX: 10, CON: 10, INT: 10, WIS: 10, CH ...

How can I stop one mocha it function's Typescript class scaffolding/setup from disrupting another?

Currently, I am working on writing TypeScript tests in Mocha and have defined a test scenario as follows: describe("IsDefined", () => { it("should work correctly ...", () => { class Test { @IsDefined() p1: String = ""; ...

Having trouble with the submit form not functioning properly in the Firefox browser exclusively

Encountering an issue when submitting a form from a Bootstrap modal, specifically in Firefox. The code seems simple enough: $('#confirmBtn').click(function(e){ e.preventDefault(); $('#s-form').submit(); }); This function is ...

I am trying to make my CSS divs remain in the exact same position on the background image, even when the browser is resized both horizontally and vertically. How can I achieve this?

I need the red dot divs to remain fixed on a world map, regardless of browser resize. Not sure if I should be adjusting div properties or background. Here's my CSS code, any feedback is appreciated as I'm new to web design: HTML: <!DOCTYPE ...

Establish the container with a specific height and enable scrolling functionality

Here is the code snippet I am currently working with: <section class="table"> <div class="table-row"> <div class="table-cell"></div> <div class="table-cell"></div> <div class="table-cell"></div> ...

Exploring the functionality of dimensions in d3 parcoords

I am diving into the world of d3 and experimenting with Behold, a simplistic example directly from the website. <script src="http://d3js.org/d3.v3.min.js"></script> <script src="d3.parcoords.js"></script> <link rel="stylesheet" ...

Eliminate the use of 'sip:' when dialing the number

I am currently using the softphone eyebeam to make calls. Whenever I click on a SIP link like this: <a href="sip:0123456789">0123456789</a> The issue arises when eyeBeam adds the "sip:" prefix before the number, causing it not to recogniz ...

Foreign key is not being posted when submitting the form using Laravel and Vue

My dilemma involves managing two tables. Here is the structure of each: Table one, referred to as "parties", consists of the following fields: public function up() { Schema::create('parties', function (Blueprint $table) { $table-> ...

Scrolling the inner container in a CSS flexbox layout: tips and tricks

I'm currently working on designing a flex box based HTML layout like the one shown in the image link provided below. https://i.stack.imgur.com/nBl6N.png The layout should consist of 3 rows within the viewport with the following structure: - top: " ...

Unable to locate AngularJS controller

As my single controller started to become too large, I decided to split it into multiple controllers. However, when I try to navigate to /signup, I encounter an issue where my UserController cannot be found. The error message states: Error: [ng:areq] Argu ...

In a designated paragraph, set the display of all <span> elements to none using JavaScript

I have a long paragraph with over 10,000 lines of text and I need a way to quickly remove all the lines without hiding the entire paragraph. Specifically, I want to hide each line individually by changing the span style from "display:block" to "display:non ...

What is the best way to use Bootstrap to position form input at the bottom of a page?

Does anyone have any tips on aligning a bootstrap form input to the bottom of the page? I've tried a few different methods but haven't had any luck. Here's how it looks currently. And here's how I'd like it to look. I'm aim ...

Leverage PHP to integrate JSON data for consumption by JavaScript

I've been exploring the integration of React (JavaScript) within a WordPress plugin, but I need to fetch some data from the database for my plugin. While I could retrieve this data in JavaScript using jQuery or an API call, because the data will remai ...

What is the most efficient way to transfer a large volume of documents from mongoDB using http?

I'm dealing with a large mongoDB database that contains millions of documents and I need to fetch them all at once without crashing or encountering cursor errors. My goal is to send this data over http using express in nodeJS. The collection contains ...

Adjust the Bootstrap 4 HTML code to eliminate the rounded edges on the parallax jumbotron

I am currently working on a captivating parallax effect for my homepage, but I'm looking to eliminate the rounded corners from the images. Below is the HTML code for one section: <div class="jumbotron paral paralsec1"> <h1 class ...

transfer chosen data from a text box to a dropdown menu

Looking for: I am in need of a feature where users can input a movie title in a textbox and upon clicking the "move to selectedlist" button, the entered movie title should be added to a dropdown list that displays all the movies selected by the user. Addit ...