Is there a better way to remove the hidden attribute from p2 since calling removeAttribute() doesn't appear to work?

Is there a way to successfully change the attribute of an object using removeAttribute to remove its hidden status? I've been attempting this but haven't had any luck so far.

It seems like my code isn't having any effect. Could I be making a mistake somewhere?

function changePage() {
    document.getElementById.("p2");
    p2.removeAtribute.("hidden") ;
}

I've also attempted to condense it into a single line like this

function changePage() {
    document.getElementById.("p2").p2.removeAtribute.("hidden") ;
}

Answer №1

I have never encountered the practice of using dots before opening parentheses before.

For example:

document.getElementById.("p2").p2.removeAtribute.("hidden")
should actually be
document.getElementById("p2").removeAtribute("hidden")

(Also, referencing the element by id after retrieving it is unnecessary.)

The first example didn't work because you retrieved the element but did not take any action with it, and then tried to access a p2 variable that was not defined. Additionally, there is a . before the parentheses.

Here is an example in JavaScript:

function changeVisibility()
{
var p2 = document.getElementById('p2');
  
  switch (p2.style.visibility)
  {
  case 'hidden':
    document.getElementById('p2').style.visibility = 'visible';
      break;
    case 'visible':
      document.getElementById('p2').style.visibility = 'hidden';
      break;
  }
}
<div id="p2" style="visibility:hidden">
test
</div>
<br />
<button onclick="changeVisibility()">
  change visibility with basic js
</button>

And here is an example using jQuery:

function changePage()
{
$('#p2').toggle();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="p2" style="display:none">
test
</div>
<br />
<button onclick="changePage()">
  change visibility with basic js
</button>

The basic JavaScript version uses the visibility style, which only makes the element invisible without collapsing it.

jQuery has a convenient built-in .toggle function that alters the display of the element. It collapses the element if it is hidden and displays it according to the display style when visible. Implementing this functionality in basic JavaScript would require more effort as you would need to track the state if you want to make the method reusable. jQuery can mimic the basic JavaScript version by using CSS properties, but toggle is simpler and more elegant.

Your main issue was mixing element retrieval with methods exclusive to jQuery objects. I recommend reviewing jQuery tutorials on basic accessors for getting elements by id, class name, etc.

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

What is the best way to smoothly transition in an image that is dynamically set using Angular?

I am using Angular to set a background image for my page, but the current loading behavior is not visually appealing as the image loads from top to bottom. I would like to implement a fade-in effect or load the image from a blurry view to enhance the user ...

Constructing a new mongoose request without nesting by sending multiple requests

Currently, I am working on an application where I receive a POST request with two variables. I then extract information from three collections based on these variables and use the collected data to make a save request to another collection. The structure o ...

Playing sound files on Angular using Howler.JS

I am currently trying to incorporate the ability to play an mp3 file within a Cordova + Ionic hybrid app. The sound file is located at: www/sounds/dubstep/sound.mp3 I am attempting to play the file from a service placed in /www/scripts/services/global.j ...

Discovering the clicked element using JavaScript: A complete guide

Let me start by saying that I have come across similar posts about tracking event listeners, but in my specific case, I am struggling to figure it out. While I am familiar with the event.target property, I just can't seem to make it work. Here is a s ...

struggle with converting JSON string into an array from server

After receiving JSON data from the server, I attempted to convert it into an array using: JSON.parse(response.data.blocks) However, I encountered this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<an ...

How to Override package.json Scripts in NPM

Is it possible to modify package.json scripts without changing the original file? I need to customize the memory allocation for a specific step, but altering the package.json will affect everyone. For example, our current script is: "script": { "dev": ...

Issue with JQuery delay functionality not activating correctly upon clicking an <a> tag

When I click on an <a> tag, I want to display a div and wait for 10 seconds before redirecting. However, the div is currently being shown immediately without waiting. Here is the HTML code: <a class="clickHereToDisplay" href="http://www.google.c ...

Creating a data structure using jQuery/JavaScript when submitting a form - a guide

Currently, I am attempting to gather form input values and organize them into an array of objects that will then be sent to MongoDB. However, I am facing difficulty in figuring out how to include an array within the objects (refer to the comment in the cod ...

Configuring Google Maps API (including charts) for maximum height of 100%

I am having trouble getting my map to display at 100% height using the Google Maps API. I've encountered similar issues in the past with the Google Charts API as well. From what I've gathered, it seems like setting the height of the html and bod ...

Issues with React - Material UI Menu functionality

I'm encountering an issue with the menu/menu item component from material ui when trying to render it based on a condition. Here is my code snippet... const AddSelectItemButton = () => { return ( <> <Fab ar ...

Learn how to efficiently apply styles to multiple objects within an array using the material-ui library

Currently, I'm utilizing the functional component of React.js. Within this component, I have an array of objects that contain specific styles. const data = [ { id: 1, color: '#000' }, { ...

In TypeScript, use a Record<string, any> to convert to {name: string}

I have developed a custom react hook to handle API calls: const useFetch: (string) => Record<string, any> | null = (path: string) => { const [data, setData] = useState<Record<string, any> | null>(null); var requestOptions: Requ ...

Is there something I'm overlooking, or is this behavior unusual for an "if statement"?

I am facing an issue with returning a value from a function. It seems like a simple task - just looping through my HTMLElements and returning the one I need. This problem is new to me, and I have spent a considerable amount of time debugging the code and ...

The line break refuses to concatenate

I've been grappling with trying to format and print a 9x9 2D JavaScript array into a grid, but for some reason I can't seem to get the line breaks right. Instead of displaying the array in a neat square grid, it's all coming out in a single ...

Show labels for data on a circular graph using angular-chart.js

I recently created a pie chart using angular-chart.js and it's functioning smoothly. However, I'm facing an issue with displaying the data value on each section of the pie chart. My attempt to use Chart.PieceLabel.js by adding the code snippet b ...

When transferring Next Js static assets to Plesk, a 500 internal server error is encountered

I've successfully deployed a Next.js app to Plesk hosting after a lot of troubleshooting. However, I'm encountering 500 internal server errors in the console when trying to access the static assets. Here's an example: GET https://nextjs-test ...

Tips for preventing cursor tooltips from going off the screen

I've been working on creating a popup box that displays text positioned away from an element when the cursor hovers over it. Check out a simplified demo here. Currently, the popup box collapses when it gets close to the bounding box. I'd like it ...

Display a message if the local storage is empty

Recently, I came across a javascript code snippet that is designed to save birthday data in local storage and then display the data within a div element. The current functionality only shows nothing if the storage is empty. However, I require it to display ...

No invocation of useEffect

I am facing an issue with my React app at the moment. My high-level useEffect is not being triggered, although it works in another project with similar code. Typically, the useEffect should be called every time I make an HTTP request from the app, but noth ...

Can you explain how to achieve auto-assigning arrays in JavaScript similar to the PHP feature?

I'm seeking a way to update a JavaScript array automatically, without specifying a key as a number or string. The value should simply take the next available numeric key in the array. In PHP, you can achieve this using: <? myarray = array(); mya ...