Understanding the functionality of the setAttribute method

When attempting to toggle between the classes 'fa fa-angle-up' and 'fa fa-angle-down', I am encountering issues. The command seems to only work intermittently. Could you please review this code snippet for me? Thank you.

if(iconSubmenu[0].getAttribute('class') == 'fa fa-angle-down'){
    iconSubmenu[0].setAttribute('class','fa fa-angle-up')
}
else{
    iconSubmenu[0].setAttribute('class','fa fa-angle-down');
}

An error occurred: Uncaught TypeError: Cannot read property 'getAttribute' of undefined
    at HTMLLIElement.showSubmenu.onclick

Answer №1

function myFunction() {
  document.getElementsByTagName("H1")[0].setAttribute("class", "democlass"); 
}
.democlass {
  color: red;
}
<html>
<head>
</head>
<body>
<h1>Hello World</h1>

<p>Click the button to add a class attribute with the value of "democlass" to the h1 element.</p>

<button onclick="myFunction()">Try it</button>
</body>
</html>

This example demonstrates how to set and get attributes in JavaScript. First, you retrieve the current value and then set it to the desired element to modify its attribute.

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

Ways to eliminate jquery that has been dynamically added

Currently working with C# and loading a jQuery file 1.8.1 in the layout, but encountering an issue where another module is pulling through an additional jQuery file 1.6.1. Is there a method to dynamically remove this unwanted file without manually going in ...

Can a constant value be dynamically defined in Typescript?

Trying to dynamically define a constant in Typescript has proven to be more challenging than I anticipated. Here's what I attempted: define(name: string, value: any): boolean { var undef; const name = value; return name == undef; } ...

upright scrolling mouse slider

In my project, I have implemented a vertical slider with mousewheel control using SwiperJS from https://swiperjs.com/. Although the slider is working perfectly fine, I am looking to fix the positions while scrolling on the page similar to the example pro ...

I am encountering an issue where my useState value is coming back as undefined after I fetch data. It appears that the useState hook is

import React, { useEffect, useState } from 'react'; function MainContent() { const [objectsArr, setObjectsArr] = useState(null); useEffect(() => { async function fetchData() { let response = await fetch('http ...

How do I incorporate a smooth transition effect for opacity in this slideshow code? Part Two

Sorry to bring this up again, but I have made some progress since yesterday. However, I am still unable to complete it, and I'm starting to feel a bit desperate. If you recall, the question I posted yesterday can be viewed here: How can I add opacity ...

Using Selenium with C# to input text into an HTML <input> tag is not functioning properly

I need help figuring out how to fill in an input field on a website using HTML. Here is what the section of the website () looks like: <div class="flex-item-fluid"> <input autocomplete="username" autocapitalize="off" ...

Activate jqGrid's navigation bar save icon when the ondblClickRow event is triggered

After setting the jqGrid row edit on the ondblClickRow event, how can I enable the save icon on the navigation bar when a row is double clicked? ondblClickRow: function (rowid) { jQuery(this).jqGrid('editRow', rowid, true, null, null); ...

Exploring the `zoom` CSS attribute and adjusting font sizes on Safari

While my website is somewhat responsive on desktop, the display on iPad or tablet-sized devices leaves much to be desired. Despite having an acceptable layout, everything appears too large, making navigation difficult. It's worth noting that my websit ...

When new text is added to Div, the first line is not displayed

One of the divs on my page has an ID of "TrancriptBox" and contains multiple lines of text. When I scroll through it on my iPad, everything works fine. However, if I scroll and then change the text within that div, it doesn't display the first line o ...

Stretch element to reach the edge of the container

I need help with positioning an input and a textarea inside a container that has a height of 52.5vh. I want the textarea to start right below the input and expand all the way to the end of the container. How can I achieve this layout? Both elements should ...

Are promises perpetually in a state of limbo? (incorrect format

As a newcomer to node.js, express, and ES6, I am learning the ropes and trying to write cleaner, more efficient code using ES6 functions and promises. One issue I'm facing is with inherited functions and values, particularly next(). Here's the co ...

When it comes to mapping routes in the express framework of Node.js

Currently, I am facing an issue while setting up the route in my app.js file. The route for the listing of flights is passed in the routes/flights.js file. When I define the route at the bottom of all routes, it results in a 404 error. However, if I place ...

What are some strategies I can use to prevent issues with my web design while updating bootstrap?

I recently updated Bootstrap CDN from version 4.0.0 alpha to beta this morning. Here is a snapshot of how the web page looked before (still under construction): Website with Bootstrap 4.0.0 alpha And here is how it appears now: With Bootstrap 4.0.0 bet ...

Trigger an Ajax function using a button within a Bootstrap modal

I need to trigger an ajax function after selecting an option from a bootstrap confirmation modal. The modal will appear by calling the remove(parameter) function. Any assistance would be greatly appreciated function remove(parameter){ // $("#remove-mod ...

Are there limitations on column width and count in CSS3?

While exploring the URL http://www.w3.org/TR/css3-multicol/, I noticed that it only allows you to specify either 'column-width' or 'column-count', and sometimes both using 'columns'. However, it lacks options to set minimum wi ...

Utilizing jQuery to extract the id and update its content

One of my tasks involves working with a table generated by PHP and incorporating a modal that allows users to change the text produced by the variable $l_id. I have a link with a class "eloc" that triggers the display of the modal div section. By intercept ...

Can the <article> tag and all its content be positioned in the center of the webpage?

Can the <article> and its content remain centrally aligned on the page? Check out my website here: Typically, when you visit a website, the article is positioned in the center of the page. However, in my case, the article only remains centered when ...

Issue with IE11: Flexbox with absolute positioning not sizing correctly, fills entire width instead of individual content

Here's a simple case to reproduce the issue: <div style="display: inline-block; position: relative; border: 1px solid black;"> short <div style="display: flex; position: absolute; border: 1px solid black; top: 100%; lef ...

Add together the values retrieved from various AJAX calls

I'm attempting to calculate the total value of the data returned by multiple ajax requests. However, I am facing an issue where the total is always showing as 0 because the calculation is happening before the ajax requests are completed. var totalRev ...

Creating a Python web scraper that utilizes Selenium and PhantomJS to extract DOM information

Attempting to extract data from a website that uses JavaScript to build the DOM, I employed both Selenium and PhantomJS. While the code provided below sometimes works, it often retrieves an empty website without executing the necessary JavaScript. Only oc ...