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

Every time I attempt to visit my website on a mobile device, it seems to appear larger than normal, as

After developing a responsive website and adding media queries to make it mobile-friendly, I encountered an issue. Despite my efforts, the website's width is still larger than the mobile viewport, requiring users to zoom out to view it properly as sho ...

Converting Text into HTML using Node.js

Currently, I am utilizing nodemailer to send emails from my node server. The content for these emails is fetched from a MSSQL SQL server and is formatted in plain text format, including newline characters. However, when sending the email using nodemailer, ...

Having issues with the presentation of full_numbers pagination in IE while using jQuery dataTables

I am currently utilizing the DataTables jQuery plugin (found at ) with the initialization code below: $('#reconcile_table').dataTable( { 'bSort' : true, 'bFilter' : true, 'bSortClasses' : false, &a ...

Refresh the angular form after submitting data

I am currently working on an angular form to input data into a database. My framework of choice is angular-fullstack by yeoman. After successfully submitting the data, I encounter an issue where clearing the form values doesn't allow me to add new en ...

How to convert an array of keys and an array of values into an array of objects using JavaScript

My question is similar to the one found here: Merging keys array and values array into an object using JavaScript However, I am unable to find a solution for my specific scenario. If I have these two arrays: const keys = ['x', 'y', &ap ...

Modify the width measurement from pixels to percentage using JavaScript

Looking for some help with a content slider on my website at this link: . I want to make it responsive so that it adjusts to 100% width. I managed to make it responsive by tweaking some code in the developer tools, but now I'm stuck. The bottom two p ...

Creating pathways in AJAX with Rails

Issue at hand: undefined variable article_id. The objective: Setting up the correct route for AJAX and Rails. What I require: The format articles/1/comments/2. Main goal: To specifically load comment through AJAX, not article. In the current AJAX scrip ...

Why is my JSON object showing up as undefined in my Node.js POST request?

I have a CentOS server that is currently running a node.js HTTP server (code provided below). My goal is to pass JSON data from the command line by using the following CURL command: curl -X POST -H "application/json" -d '{"val1":"hello","val2":"my"," ...

Are CSS3 animations limited to working only with Webkit?

Trying to create a CSS3 animation featuring a puzzle piece on my website. Below is the code I'm using. Strangely, the animation only seems to be working on Safari and Chrome. Any tips on how to make it compatible with Firefox and Opera? Appreciate you ...

div layout; sidebar movements occur after appending div to the header

Having trouble mastering layouts, I am attempting to create a full-width header that includes a left sidebar and a right sidebar. The body is split into 5 sections: full width, left and right sidebars, center content with 3 columns, and the footer mirrorin ...

Step-by-step guide on utilizing the .change method in order to deactivate a

Can someone help me with a quick solution for this issue? I need to know how to disable a select option once the value has been changed. The option should be available on initial load, but after the user selects it for the first time, it should be disable ...

Implementing multiple content changes in a span using javascript

Having an issue with a pause button where the icon should change on click between play and pause icons. Initially, the first click successfully changes the icon from a play arrow to a pause icon, but it only changes once. It seems like the else part of the ...

Updating React JSX class based on certain conditions without manipulating the actual DOM

When working with jsx react, I am looking to dynamically set a class while keeping another class static. Here is an example of what I would like to achieve: maintaining the type class and having an additional dynamic class change change to either big, smal ...

A guide on incorporating the close button into the title bar of a jQuery pop-up window

Check out this fiddle: https://jsfiddle.net/evbvrkan/ This project is quite comprehensive, so making major changes isn't possible. However, the requirement now is to find a way to place the close button for the second pop-up (which appears when you c ...

Ways to retrieve object in Javascript

I retrieved this data object from a JSON file source. { "Apple": "Red", "Orange": "Orange", "Guava": "Green", } Afterward, I transformed it into an Object using: var data = JSON.parse(dataFromJson); which resulted in a JavaScript object ...

Enhancing audio control features using HTML and JavaScript

After utilizing various suggestions, I have successfully created a basic audio slider that starts playing sound (at zero volume) when clicked by the user. They can then adjust the volume as needed. My only challenge is that the volume adjustment only occu ...

Creating an animated sidebar that moves at a different speed than the rest of the

I have a layout with a large sidebar and small content, where the "Fixed part" refers to sticky positioning. I'm attempting to achieve this using scrollTop, but the sidebar is causing some issues like this: The code should only be executed when the ...

The functionality of React setState seems to be malfunctioning when activated

Having encountered an unusual issue with react's setState() method. Currently, I am utilizing Azure DevOps extensions components and have a panel with an onClick event that is intended to change the state of IsUserAddedOrUpdated and trigger the addOr ...

Next.js pages do not respond to event listeners

Something strange is happening in my Next.js project. I've implemented a header that changes color as the page scrolls using the useEffect hook: The hook in the Header component looks like this: React.useEffect(() => { window.addEventListener(&a ...

Tips for preventing multiple counter buttons from conflicting with one another

Currently, I am in the process of creating an online restaurant platform that allows customers to place food orders. To streamline this process, I am developing individual cards for each food item available on the menu. In addition, I am implementing butto ...