Issue with nextElementSibling not applying CSS style

My current issue revolves around a button that is designed to open or close a collapsible div. The HTML structure of this element looks like the following:

<div class='outer-collapsible'>
  <button type='button' class='collapsible'>Targets and Victims</button>
  <div class='content'>
    <p>Lorem ipsum...</p>
  </div>
</div>

While attempting to target all button elements with the collapsible class, I am utilizing nextElementSibling to select the <div class='content'> as shown below:

let collapsibles = document.querySelectorAll('.collapsible');

for (let i = 0; i < collapsibles.length; i++) {
  if (collapsibles[i].nextElementSibling.style.display == 'block') {
    // perform certain actions
  }
}

However, it appears that even though nextElementSibling successfully selects the correct div, it does not recognize any style attributes specified in my CSS file. Does nextElementSibling solely identify inline styles? While I could explore alternative methods to accomplish this task, I am curious as to why nextElementSibling correctly identifies the element but fails to detect the styling accurately?

EDIT:

CSS

.collapsible {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.active,
.collapsible:hover {
  background-color: #ccc;
}

.content {
  padding: 0 18px;
  display: none;
  overflow: hidden;
  background-color: #f1fff8;
}

Answer №1

When dealing with CSS styles, the issue is not related to nextElementSibling, but rather how one detects CSS style in the first instance.

The use of .style is limited to accessing the contents of the style attribute, like

<div style="color: red"></div>
.

To access the "real" styles, one should consider using .getComputedStyle().

Answer №2

Styles can be applied to different elements using a variety of selectors such as id, class, and position. The specificity of a selector determines how it will override other styles. Inline styles in HTML have the highest specificity, making them less flexible and not recommended.

When accessing the .style property in JavaScript, you are directly modifying the inline style of an element.

It is more advisable to work with CSS classes and add/remove them as necessary. The use of the classList API in JavaScript simplifies this process:

let collapsibles = document.querySelectorAll('.collapsible');

document.querySelector(".collapsible").addEventListener("click", function(){
    this.nextElementSibling.classList.toggle("hidden");
});
.collapsible {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

/* Use this class for showing/hiding content */
.hidden { display:none; }

.active, .collapsible:hover {
  background-color: #ccc;
}

.content {
  padding: 0 18px;
  overflow: hidden;
  background-color: #f1fff8;
}
<div class='outer-collapsible'>
      <button type='button' class='collapsible'>Targets and Victims</button>
      <div class='content hidden'>
        <p>Lorem ipsum...</p>
      </div>
    </div>

Answer №3

According to the resources on Mozilla's website here

It is important to note that the style property may not provide a comprehensive overview of all styles applied to an element. This is because it only represents CSS declarations present in the element's inline style attribute, and does not include styles from other sources such as external style sheets or style rules in the document section. To access all CSS properties for an element, it is recommended to use Window.getComputedStyle() instead.

Therefore, using the style attribute alone may not be sufficient to access styles defined in external stylesheets.

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

Dynamically adjust the label position based on the button position

I am currently developing an interface that allows users to change the position of buttons and add a label text under the button. However, I am facing an issue where the label is not always centered below the button due to variations in the size and number ...

The div reveals a submenu by popping out when its overflow is set to hidden

I am trying to figure out how to create a horizontal menu with sliding option and submenu. The issue arises when I set overflow to hidden for the sliding effect, as it causes problems with the submenu. Any suggestions or ideas on how to solve this dilemma ...

Is there a way to transfer the value from one directive to another directive template and access it in a different directive's scope?

I attempted to pass the directive attribute value to a template ID, which can then be used in another directive. Below is my index.html code: <my-value name="jhon"></my-value> Here is the JavaScript code: .directive('myValue',func ...

Obtain the form value upon submission without the need to reload the page

I am facing an issue where I have a form and I want to trigger the display of a div (in the same page) and execute a JavaScript function upon clicking submit, all without causing a page refresh. <form action="#" method="post" name= "form1" id = "form ...

quickest method for retrieving a property by name, regardless of its location within the object hierarchy

I am looking for a solution to retrieve the value of a property from an object graph, and I am wondering if there is a more efficient alternative to the method I have outlined below. Instead of using recursion, I have chosen tree traversal because it cons ...

What changes can be made to the HTML structure to ensure that two form tags function separately?

Hey there! I'm currently tackling a web project that involves incorporating two form tags on one page, each with its own distinct purpose. Nevertheless, it appears that the inner form tag isn't behaving as it should. My suspicion is that this iss ...

Is it possible to pass a variable from an Axios Response in the Composition API up to the root level?

I need to fetch the headings array from an axios.get call and utilize it at the root level within my Vue component. However, when I attempt to return it, I encounter this error: ReferenceError: headings is not defined Here is the script element in my Vue3 ...

Combine Immer and NgRx reducer for improved state management

Upon analyzing redux and ngrx, it appears that immer is the preferred library for creating a copy of the state before storing it. In following the example provided by immer, I implemented the following code in my reducer: on(exampleActions.updateExample ...

RMarkdown Question: Is there a straightforward method to insert additional space following each tabset?

When creating reports using R Markdown, I implement tabsets (.{tabset}) to display multiple results without stacking them one after the other. For example: # First session {.tabset} ## A First result ## B Second result # Next session Howev ...

Every time I attempt to run "npm install" on Visual Studio Code, I encounter an error

Every time I try to run npm install, I encounter this error. My node version is 18.9.1 and I have exhausted all possible solutions. Any help would be greatly appreciated. '''npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Us ...

The process of implementing web-based online diagramming software involves a strategic approach to designing and integrating various

I'm really interested in learning how web-based online diagramming software works. If anyone could provide guidance or point me to example resources, I would greatly appreciate it. Here are some of the web-based online tools that I have been explorin ...

Displaying an external webpage within a Backbone application

Is it feasible to display an external webpage in a view by using its URL? I am working with Backbone and Handlebars. var AuthorizeInstagramView = Backbone.View.extend({ template: Handlebars.compile(template), initialize: function () { }, ...

`There is a delay in rendering the background image on Chrome`

Once I apply a class to my button element using JavaScript, the background image (.gif) that is supposed to display afterwards takes an unusually long time to render. The button serves as a form submission. Upon being clicked, a class of "clicked" is dyna ...

Scrollbar in an HTML selection tag

Is there a way to add a scroll bar to an HTML select box without using JavaScript? Alternatively, is there a JavaScript library that can achieve this behavior? Also, I'm looking for a redesign of the interface where I have two select boxes and items ...

The spread operator in Vuex is causing compilation errors with babel, as it continuously results in a module build failure

Currently, I am utilizing a spread operator within my mapGetters object. It is crucial to use a specific babel-preset-stage for proper ES6 compilation. Even after installing babel-preset-stage-2 via npm, I encountered the following error: ERROR in ./~/bab ...

Create an Array with a dynamic name derived from the values of other variables

In my JavaScript project, I am facing a challenge in naming arrays based on dynamic data such as room numbers and user IDs. As the rooms and users are constantly changing, I need to create multiple arrays accordingly. Although this code is incorrect, it s ...

What could be causing the malfunction of this JavaScript dropdown select feature in Internet Explorer?

I created a website that requires users to input their location, including the city and state. The process involves two dropdown menus: - The first dropdown menu, labeled "state," loads all USA states as selectable options when the website is loaded. This ...

Customizing the styling of a TextField component in ReactJS using material-ui

I am currently working with Reactjs and material-ui. I am looking to apply some custom styles to a TextField using css. Specifically, I would like to change the color of the TextField underline and label when the input is clicked. Although I know it can b ...

Date range within a conditional statement

I have encountered this code snippet: function auto_select_param_call_time() { if (today() == date("02.01.2017") || today() == date("03.01.2017")) { auto_click_param("call_time", "Non-working day"); } else { //Do something else ...

What is the best way to use toggleClass on a specific element that has been extended

I have been experimenting with this code snippet for a while. The idea is that when I hover my mouse over the black box, a red box should appear. However, it doesn't seem to be working as expected. Could someone please review this script and let me k ...