Creating a fresh CSS class and utilizing its properties in JavaScript is the task at hand

Whenever I define a css class and attempt to access its member from JavaScript, the result always ends up being undefined. Where could my mistake possibly lie?

function myFunction() {
  var x = document.getElementById("myId").style.myMember;
  document.getElementById("debug").innerHTML = x;
}
.myClass {
  myMember: 123;
}
<p>Click the button to get the style property of the myId element.</p>

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

<p id="debug"></p>

<div id="myId" class="myClass">
  My content.
</div>

If you wish to experiment with this concept, here's an example available on w3schools.


Providing some context: I'm currently working on a minimalist slideshow page design. Following guidance from w3schools (yes, I realize it's quite mainstream), I've managed to create the slides in CSS.

My objective now is to set different display times for each slide within the HTML file while having a default value in case any time entry is omitted.

In my mind, incorporating the display time into the style of the slide seemed to be a logical approach. However, based on the responses received so far, it appears that custom attributes cannot be appended to CSS styles. Is that understanding accurate?

What would be the correct method to transfer a display time from this HTML snippet:

<div class="mySlides fade">
   <img src="img.jpg" style="width:100%">
</div>

to this JavaScript function?:

function carousel() {
    var i;
    var x = document.getElementsByClassName("mySlides");
    for (i = 0; i < x.length; i++) {
      x[i].style.display = "none"; 
    }
    slideIndex++;
    if (slideIndex > x.length) {slideIndex = 1} 
    x[slideIndex-1].style.display = "block";
    setTimeout(carousel, 500); // Retrieve display time from HTML instead!
}

Answer №1

In the first place, the element.style object will provide you with the style values that are specifically defined within that particular element...

Furthermore, myMember is not a valid CSS property, so it won't return any value...

function myFunction() {
  var x = document.getElementById("myId").style.display;
  document.getElementById("debug").innerHTML = x;
}
<p>Click the button to retrieve the style property of the myId element.</p>

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

<p id="debug"></p>

<div id="myId" style="display:block">
  My content.
</div>

Answer №2

By typing "document.getElementById("myId").style" in the console, you will receive all relevant styles for your selected element. The class "my123" is not identified within that context, hence resulting in an undefined outcome.

Answer №3

When attempting to declare "myMember" as a property for use in Javascript, it may be returning undefined because myMember is not recognized as a CSS property.

In Javascript, the style property returns a CSSStyleDeclaration object that corresponds to an element's style attribute.

This style property can be utilized to access and manipulate specific styles of an element by utilizing various CSS properties.

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

Unexpected behavior with async pipe - variable becomes undefined upon reassignment

In my development process, I have implemented 2 components. One is responsible for fetching data from an external service, while the other one displays this data. The constructor of the first component is structured as follows: constructor( private dev ...

A guide on integrating functions into dynamically created buttons using the DOM

Is there a way to add functionality to the button labeled "CLICK ME TO EDIT"? I'm looking for some ideas on how to do this. var comment = prompt("Type content for new paragraph here", ""); var newParagraph = document.createElement('p'); new ...

Struggling to access FormData in php

I'm having trouble retrieving variables from FormData in PHP after making an AJAX call. What could be causing this issue? Here is the snippet of my JavaScript code: var sendData = new FormData(); sendData.append('itemid',$('select#sel ...

Angular: Handling window resizing events in your application

To handle window resize events in a non-angular application, we typically use the following code: window.onresize = function(event) { console.log('changed'); }; However, in angular applications, it's not recommended to directly acc ...

Determine whether an input is currently in a "checked" state

I am working with this simple HTML layout: <fieldset> <input/> <label></label> <div class="toggle_box"> <div class="switch"></div> </div> </fieldset> My goal is to achieve the ...

Place a checkbox at the start of each table cell

Is there a way to add a checkbox before the text in the first cell of each row in an HTML table using jQuery? I attempted this method: $("table td:first-child").each(function() { $(this).prepend('<input type="checkbox" class="basic-kpi-row"/&g ...

ReactJS attempting to invoke a class function using a dynamically generated button

When attempting to access the deletePost(index) method from the ShowPost class using a dynamically rendered button within the render() step in React, I encounter an issue. The button labeled "click me" successfully retrieves and prints the first item in my ...

Using AngularJS, you can easily merge one array of data into another array

In my coding environment, I am working with two arrays. The first array is called `$scope.workingSchedules` and it contains data related to working hours for different days of the week. $scope.workingSchedules=[ { ...

Display the Ajax response in a designated div

I am facing an issue with my ajax code. It doesn't print any output, but when I use alert() to print the output, it shows up fine. $(".grp-ans").each(function(e){ $.ajax({ type: 'POST', url: 'show-answ ...

Unable to get the sublocality dropdown list to cascade properly in asp.net mvc

I am dealing with three dropdown lists. The initial action method for the City dropdown is shown below: public ActionResult Create() { List<SelectListItem> li = new List<SelectListItem>(); li.Add(new Sel ...

JavaScript Canvas - Preserve Image Transparency

I have been trying to download a snapshot of a canvas using the code below: var strMime = "image/png"; var canvas = document.getElementsByTagName('canvas')[0]; var link = document.createElement("a"); link.href = canvas.toDataURL( ...

Can we include intricate items within a redux store?

As I delve into developing a React application with Redux, I encountered an unexpected scenario. At one point, we inserted a DOM element within the store, causing issues with the Redux extension that freezes when the action is triggered. Despite this compl ...

Limit the rotation of jQuery and CSS3 elements to always turn in a clockwise direction

Utilizing the jQuery transit plugin, I am rotating a block element with 4 navigation controls. Each time a nav item is clicked, the block rotates to the specified custom data attribute of that nav item - either 0, 90, 180, or 270 degrees. While I have suc ...

Experiencing difficulty with setting up the ReactJS pagination component

Each time I click on a page number, the maximum size of the pages is returned as a handler parameter (for example, clicking on 2 returns 4). What could be causing this issue? UPDATE class PagingControl extends React.Component{ constructor(props) { ...

The protection ensured by employing an extensive hash in the query string for the recognition of a changing document

I am currently developing a small web application that creates exercise program printouts. The concept is simple - a user like a personal trainer can craft an exercise regimen and send it to their client via email using a unique link. http://www.myurl ...

recursive algorithm utilizing an array as an argument

Currently, I am in the process of developing a function that extracts chest exercises from an array titled "chest". This particular function is required to randomly select multiple exercises, achieved by utilizing a random pointer. In order to avoid selec ...

How can we enhance Backbone.sync() at the Model level to include additional parameters?

Currently, I am facing a challenge with overriding Backbone's sync() method for a Model. I have the function signature set up and it is triggered correctly, but I am unsure about what needs to be included in the function body in order for it to automa ...

Why is the lower right white space left unfilled by the color red?

I'm having issues with using named lines in grid for layout. The red section is not positioning correctly next to the footer, and I can't figure out where I went wrong. * { box-sizing: border-box; margin: 0; padding: 0; } .container { ...

What is the method for attaching multiple listeners to an element?

For example: v-on:click="count,handle" I posted this question in the Vue gitter channel, but received advice to use a single listener that triggers others. If using one listener is the recommended approach, I am curious to understand why. Is having multi ...

Preventing an infinite re-render loop caused by event listeners in React

One functional component is causing me some trouble: export default function Nav({photo}) { const [isOpen, setIsOpen] = useState(false) const [width, setWidth] = useState(window.innerWidth); const breakpoint = 768; useEffect(() => { ...