JavaScript: Applying styling based on the presence of a specific class in neighboring child elements

After checking related answers, I haven't found what I am looking for. Apologies if this is a duplicate question.

This specific HTML code is used multiple times on a page, within a product box, and is displayed on a product category page.

<div class"all-buttons-container">
    <div class="button1-container">
        <a class="button1">text</a>
    </div>
    <div class="button2-container">
        <a class="button2 **hidden**">text</a>
    </div>
</div>

In this simplified HTML structure, there is a container with two sibling elements. - Each sibling contains an anchor element.

  • The button containers are always visible.

  • Sometimes, the .button2 anchor also has the bootstrap class of hidden, hiding the anchor. This is controlled within each product box based on the need for a second button. I have no control over this aspect.

  • If the .button2 anchor has the hidden class, I need to add some margin-top to the button1-container in order to vertically center it.

I initially considered using pure style (flexbox) but it didn't achieve the desired result.

I am exploring the option of running a jQuery or pure JS script every time the page finishes loading to automatically add the necessary top margin to each instance of this HTML, if needed. While I prefer not to do this, it may be required if I cannot find a simpler solution.

Any suggestions or solutions would be greatly appreciated!

Thank you in advance!

Cheers, Wayjo

Answer №1

It seems like I've grasped the gist of your query.

To accomplish this task without Javascript, consider a more structured approach. How about creating a unique class named button2-hidden and associating it with the container named all-buttons-container?

<div class"all-buttons-container button2-hidden">
    <div class="button1-container">
        <a class="button1">text</a>
    </div>
    <div class="button2-container">
        <a class="button2">text</a>
    </div>
</div>

Afterward, you can implement the following CSS:

.button2-hidden .button2-container{
  display: none; // or use visibility -- as per your preference
}
.button2-hidden .button1-container{
  margin-top: 1rem;
}

Answer №2

If you want to include a div to hold the buttons, you can use the code snippet provided below:

.all-buttons-container{
  display: flex; /* key point */
  align-items: center;  /* key point */
  padding: 10px;
  background-color: grey;
  width: 200px;
  border: 2px solid #fff;
  height: 150px;
}
.hidden {
  display: none!important;
}

.all-buttons-container > div a{
  display: inline-block;
  background-color: blue;
  padding: 7px;
  margin: 7px;
  color: #fff;
}
<div class="all-buttons-container">
  <div class="very-important-div">
    <div class="button1-container">
        <a class="button1">button1</a>
    </div>
    <div class="button2-container">
        <a class="button2">button2</a>
    </div>
  </div>
</div>

<div class="all-buttons-container">
  <div class="very-important-div">
    <div class="button1-container">
        <a class="button1">button1</a>
    </div>
    <div class="button2-container">
        <a class="button2 hidden">button2</a>
    </div>
  </div>
</div>

<div class="all-buttons-container">
  <div class="very-important-div">
    <div class="button1-container">
        <a class="button1 hidden">button1</a>
    </div>
    <div class="button2-container">
        <a class="button2">button2</a>
    </div>
  </div>
</div>

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

PHP does not automatically escape HTML special characters

Within my ZF2 application, there is a .phtml layout that includes the following code: <p>Created in 2015 <?php echo htmlspecialchars("by Jérôme Verstrynge",ENT_HTML5); ?></p> However, when I review the source of the pages returned by ...

Angular - Issue with Select Element - NgFor directive is limited to binding with Iterable objects like Arrays

I have a REST API build in NodeJS that sends me JSON data as a response. I utilize this data to populate the options of a select input element: [{"id":1,"tasktype":"Programming","taskvalue":350,"date":"2018-08-02T03:00:00.000Z","status":1},{"id":2,"taskty ...

What is the best way to retrieve a promise from several promises?

Every time I check the console, I see the following: teamsUpdated2 addUserToProjects deleteUserFromProjects However, they should be displayed in a different order. var result = teamService.addOrDeleteUser(userId, newTeams, deleteTeams); result.then(fun ...

React with radio button selection ignoring any null values

Currently, I am in the process of creating a personality quiz application by following a tutorial I discovered online at //mitchgavan.com/react-quiz/. In my project, there is a file called quizQuestions.js that serves as an API to fetch both the questions ...

Add a selection of paths from a different package into the Router

Seeking a quick solution here. I have the following code snippet and I am looking to efficiently import a multitude of routes from my package. These routes should be managed by the package I am constructing. If I introduce a new page in the package (e.g., ...

Create a unique inset shadow that surrounds all elements of the content

I'm having trouble figuring out how to create a 4px inset box shadow border that surrounds all of the content. Currently, the box shadow fills the window perfectly (as shown in the fiddle below), but my fixed navigation bar at the top ends up above th ...

Issue encountered while attempting to start React and Node.js: NPM error

I've encountered some errors in my Node.js and React.js project. I have a server and a React SPA, both working independently. When I use "concurrently" to start them together, I get the following errors: [0] npm ERR! missing script: servernpm run clie ...

Troubleshooting issues with creating a table using the "mysql_fetch_array();" function

Currently, I am working on building a webpage that retrieves data from a database and displays it in table format. However, my attempt to use the "table border" and "table-height" commands seems to have gone awry. The issue I am facing is that even thoug ...

Best practices for managing an array of buttons and handling click events in ReactJs

While working on my react class component, I encountered an issue. The alert popup keeps appearing constantly without any button click as soon as the component renders. onHandleOnClick(data, e) { console.log(data); alert("got it" + data); } rend ...

What is the best way to ensure that my theme button changer has an impact on all pages throughout my website, not only on the

Looking for some help here - I've got a button that changes the theme/colour of my website, but it only seems to work on the homepage and not on any other pages. Anyone know how I can fix this issue? Here's the JavaScript code: $(document).ready ...

How to show or hide a textbox in JavaScript?

Within my user control, there is a panel with two controls: ddlType, a drop-down list, and txtOthers, a text box. Initially, txtOthers is set to be invisible. The goal is for txtOthers to become visible when the user selects an option in ddlType that corr ...

Upon loading, make sure to click on the link located within the third <li> tag

I am working with a list (<ul>): <ul class="options_inner"> <li><a data-dk-dropdown-value=".option1"></a></li> <li><a data-dk-dropdown-value=".option2"></a></li> <li><a data- ...

CSS styling for a background image in the header

Why isn't my background image showing up even though I've used a direct link to the image? What could be causing this issue? .header { background-image: url("https://www.africa.com/wp-content/uploads/2015/07/Kenya.jpg"); background-attac ...

What are the necessary steps for incorporating Payment/Bank transactions into an e-commerce platform?

Right now, I'm utilizing HTML, CSS, jQuery, and some JavaScript to develop a website. As I work on creating the store section, I find myself unsure of how to incorporate payment methods and all related features. Are there any free "pre-built" systems ...

Styling radio buttons with CSS

I've been struggling to align my radio buttons next to their labels. Despite numerous changes to the CSS, I can't seem to get my text boxes, radio buttons, and comment box to line up properly. Specifically, the second radio button is causing alig ...

Add up the duplicate elements in two arrays

I have dynamically created two arrays with the same number of cells (where array.length is the same, representing a key and value association). Below are the arrays: barData.labels["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "F ...

Automatically populate editbox in Magento upon exiting

I'm facing a seemingly simple question but struggling to find a solution. I have a frontend form with various input boxes where users can enter a blog URL. Upon exiting the box, I want to: Extract and retrieve tags related to the OpenGraph protocol ...

Using Bootstrap to create a fixed footer in Laravel

I have a Laravel project with Bootstrap added as the CSS. I have tried everything to make my sticky footer work, but when the page is longer than the window, it remains at the bottom of the window when scrolled up. Here is my main: <html> <head& ...

Verify the validation of the text box

Checking a textbox control for validation is necessary. Validation Criteria: Value should be between 0 and 1000, with up to 2 decimal places (e.g. 1.00, 85.23, 1000.00). Once 2 decimal points are used, users should not be able to enter additional ze ...

Is it possible to form a union type using an interface?

My goal is to call the function getSvgPresentationAttribute using any valid CSS property name as cssStyleAttribute. However, I am encountering an issue with my current code where I receive the error message Type 'CSSStyleDeclaration' cannot be us ...