Using the getElementById function in javascript to modify CSS properties

Here is the setup I am working with:

<div id="admin">

This element has the following style applied to it:

display: none;

I am attempting to change the display property when a button is pressed by defining and utilizing the following JavaScript code:

var admin = document.getElementById('admin');
admin.style.display = "block";

Initially, this solution works correctly. However, when I modify admin to admin-panel, as shown below, it stops working and throws an error stating admin is not defined(…).

<div id="admin-panel">
var admin = document.getElementById('admin-panel');
admin.style.display = "block";

If anyone could assist me in understanding why it functions in the first scenario but fails in the second, I would greatly appreciate it.

UPDATE

It appears that moving

var admin = document.getElementById('admin-panel');
inside the show and hide functions resolves the issue. Could this be due to variable scoping challenges as seen in the revised code snippet below?

var adminView = {
  init : function() {
    var admin = document.getElementById('admin-panel');
    this.adminBtn = document.getElementById('admin-toggle');
    this.adminCancel = document.getElementById('admin-cancel');
    this.adminSave = document.getElementById('admin-save');

    this.adminCatName = document.getElementById('admin-cat-name');
    this.adminCatUrl = document.getElementById('admin-cat-url');
    this.adminCatClicks = document.getElementById('admin-cat-clicks');

    this.adminBtn.addEventListener('click', function(){
      catController.adminDisplay();
    });

    this.render();
  },

  render: function() {
    var currentCat = catController.getCurrentCat();
    this.adminCatName.value = currentCat.name;
    this.adminCatClicks.value = currentCat.clickCount;
    this.adminCatUrl.value = currentCat.img;
  },

  show: function() {
    admin.style.display = "block";
  },

  hide: function() {
    admin.style.display = "none";
  }

};

Answer №1

The reason for this issue is that your admin variable is not accessible within the other methods. To resolve this, save it as a property and access it using this:

var adminView = {
  init : function() {
    this.admin = document.getElementById('admin-panel');
  },

  show: function() {
    this.admin.style.display = "block";
  },

  hide: function() {
    this.admin.style.display = "none";
  }

};

adminView.init();
adminView.show();
#admin-panel { display: none; }
<div id="admin-panel">Hello Admin</div>

Answer №2

To grant global access, eliminate the use of var for the admin variable.

Answer №3

Give it a shot!

<!DOCTYPE html>
<html>
<body>
<button onclick="Reveal()" >Reveal</button>
<button onclick="Conceal()" >Conceal</button>
<div id="admin-panel" style="display:none;">
testing
</div>
<p>Much appreciated</p>
<script>
function Reveal()
{
document.getElementById('admin-panel').style.display="block";
}
function Conceal()
{
document.getElementById('admin-panel').style.display="none";
}
</script>
</body>
</html>

Answer №4

It's working perfectly

<div id="admin-panel">
</div>

<script>
    var admin = document.getElementById('admin-panel');
    admin.style.display = "block";
</script>

Link to the code on jsFiddle

Is it possible to see the complete code? I suspect there might be an issue with the variable range.

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

The AngularJS Factory $http encounters an error when attempting to read the property 'length' of an undefined value

I am looking to implement a factory in my REST Controller that will return an array of Strings. I want to be able to reuse this function in my services.js file. Here is the HTML for an Autocomplete input field: <input type="text" ng-model="vertrag.ver ...

What is the reason for the index.html file not connecting to the local .css files and .js file?

I'm currently using node.js to send an .html file that includes the following tags: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="description" content="This is my personal profile website" /> <link r ...

After implementing ajax, jQuery ceases to function

I have been working with multiple JavaScript files and everything is functioning perfectly (including functions that add styles to elements), but I am encountering an issue when trying to include the following script: <script src="http://ajax.googleapi ...

What is the method for stretching the navbar and content to fill the entire viewport in Bootstrap?

Can anyone help me with an issue regarding a navigation bar and content created in Bootstrap 5? I'm trying to use vh-100 to make both the navigation bar and content stay on the view page without a scrollbar. However, the size of the navigation bar is ...

html inserting line break using label

I am attempting to dynamically set text to a label using jQuery. However, I am having trouble getting the <br> or \n to create new lines. Instead, all the text displays on the same line and wraps around. If you want to see my code in action, ch ...

Is there a way to incorporate multer middleware into my express controller without using the router?

This is the structure I typically follow when writing controllers and routes using Express controller exports.postBlog = async (req, res, next) => {...} routes router.route("/post").post(onlyAdmin, postBlog); *onlyAdmin serves as a middlewa ...

Ensure selected language is maintained when refreshing or changing view by utilizing switch i18n functionality

Hello there, I am facing a challenge with "JavaScript Localization" on my website. The issue is that I cannot figure out how to prevent the DOM from prioritizing the local language of the browser and instead use the language set in the switch as a referenc ...

Dynamically uploading an HTML file using AJAX

My webpage has a feature that dynamically creates HTML with drop down elements. Additionally, there is a "create File" button on the page. The goal is for this button to trigger an AJAX POST request and upload the dynamic page created with drag and drops a ...

Utilizing Node.js to Retrieve Data from MySQL

Hi there, I'm new to NodeJS and I'm curious about how to fetch a MySQL query like we do in PHP. $query = mysql_query("SELECT * FROM accounts"); while($fetch = mysql_fetch_array($query)) { echo $fetch['Username']; } How would this be ...

Utilizing Bootstrap in Laravel to align the heights of rows in adjacent columns

I am in the process of developing a calendar application that includes a header row and a header column. The layout displays six days in columns with a fixed number of time periods per day. <div class="row"> <div class="col-md c ...

Is it necessary to download all npm packages when starting a new project?

I recently started learning about npm packages and node. I noticed that when installing packages, they create numerous folders in the "node modules" directory. This got me thinking - when starting a new project, do I need to re-install all these packages ...

What is the best way to use jQuery to attach functions to every input element?

Imagine you have a set of HTML markup and CSS like this: #CSS .inputhelp_text { background: #000; color: #fff; } .nodisplay { display: none; } <input class="inputhelp" id="firstname" /><span class="inputhelp_text nodisplay" id="help_firstname"& ...

Cookies in Node.js Express are not being incorporated

Currently, I am in the process of developing a nodejs application and facing an issue with defining cookies. Here is a snippet of the code that I am working with: var app = express(); app.set('port', process.env.PORT || 3000); app.set('vie ...

What is the best way to implement CSS styling in the existing Vue.js template?

Currently delving into the world of Vue.js, I've discovered that styling child components is achieved by referencing classes, ids, and tags defined in the component's template. Let's take a look at the App.vue component as an example: <st ...

I'm trying to determine in Stencil JS if a button has been clicked in a separate component within a different class. Can anyone assist

I've created a component named button.tsx, which contains a function that performs specific tasks when the button is clicked. The function this.saveSearch triggers the saveSearch() function. button.tsx {((this.test1) || this.selectedExistingId) && ...

Express: simplifying the use of middleware for app implementation

I am looking to update the code in my index.js file app.use(require('sass-middleware').middleware({ src: path.resolve(__dirname, '../'), dest: path.resolve(__dirname, '../public') })); app.use(require('browserify-dev ...

Tips on ensuring data cleanliness in jQuery input fields

Before sending the ajax request, I want to sanitize the form fields for added security. Currently, my Javascript code looks like this: jQuery(document).ready(function($) { $('#login-form').submit(function(e) { e.preventDefault(); // pr ...

Extending an element beyond the boundaries of its container

I currently have 3 different divisions within the body of my document: a container, a parent, and a child element. My goal is to make the child element extend beyond its parent on the left side. However, when I try to achieve this by using position: ab ...

animation for closing the hamburger menu

Having trouble creating a hamburger menu animation. I've set up two divs - one for the basic horizontal lines and one for the X icon. Using jQuery, I can hide and show them (clicking on the lines hides them and shows the X). But now I want to animate ...

Using AJAX to load multiple pages asynchronously

Recently, I put together a website using the following script: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script> function loadpage(page) { document.getElementById( ...