Display every div element if none of the links have been clicked

On my webpage at url.com/yourfirstpage/, all div elements are hidden by default with a display:none property. If we specifically target #sec1 by going to url.com/yourfirstpage/#sec1, only sec1 is displayed while the others remain hidden. But what if we access the URL without specifying an anchor id like url.com/yourfirstpage/? In that case, all the divs should be shown.

#sec1, #sec2, #sec3{
display:none;
}
#sec1:target{
display:block;
}
#sec2:target{
display:block;
}
#sec3:target{
display:block;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>

<div id="sec1" class="page"> this is sec1</div>
<div id="sec2" class="page"> this is sec2</div>
<div id="sec3" class="page"> this is sec3</div>

Answer №1

If you need to adjust your HTML structure, here's a neat trick for you. The concept involves initially displaying the elements and then using :target to hide them. To achieve this without the ability to select previous or parent elements directly, I utilized an id within a parent element to target any specific element:

#sec1:target .page:nth-child(n+2){
  display: none;
}

#sec2:target .page:nth-child(2n+1){
  display: none;
}

#sec3:target .page:nth-last-child(n+2){
  display: none;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>

<div id="sec1">
  <div id="sec2">
    <div id="sec3">
      <div class="page"> this is sec1</div>
      <div class="page"> this is sec2</div>
      <div class="page"> this is sec3</div>
    </div>
  </div>
</div>

This method can be adapted for numerous sections, with room for enhancing the CSS code as shown below:

#sec1:target .page:not(:nth-child(1)),
#sec2:target .page:not(:nth-child(2)),
#sec3:target .page:not(:nth-child(3)),
#sec4:target .page:not(:nth-child(4)),
#sec5:target .page:not(:nth-child(5)) {
  display: none;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>
<a href="#sec4">sec4</a>
<a href="#sec5">sec5</a>

<div id="sec1">
  <div id="sec2">
    <div id="sec3">
      <div id="sec4">
        <div id="sec5">
          <div class="page"> this is sec1</div>
          <div class="page"> this is sec2</div>
          <div class="page"> this is sec3</div>
          <div class="page"> this is sec4</div>
          <div class="page"> this is sec5</div>
        </div>
      </div>
    </div>
  </div>
</div>

Answer №2

this simple method could provide a solution

utilizing the ! selector in CSS with the help of postcss plugins can achieve this effect

[...document.querySelectorAll('a')].forEach(a => {
    a.addEventListener('click', () => {
        a.parentElement.classList.add('targeted')
    })
})
.targeted div {
  display: none;
}
.targeted div:target {
  display: block;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>

<div id="sec1" class="page"> this is sec1</div>
<div id="sec2" class="page"> this is sec2</div>
<div id="sec3" class="page"> this is sec3</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

What is the best way to create a JavaScript "input" field that only accepts vowel letters?

Is there a way to create an "input" field that only accepts vowel letters? Additionally, I want to ensure that copying and dragging text into the input field will also be filtered out. <div class="field"> <input class="fie ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

Using HTML and CSS, change the background color to red based on the value of each cell in a forEach loop

Need help with my HTML/CSS code. I have a table where I need to change the background color of any row that has a cell value of "Not Approved" while using a foreach loop in Google Apps Script to send an email with two tables. What is t ...

What is the process for inserting images into a vertical timeline format?

I am currently working on building a timeline and incorporating images into it. I came across a solution on W3 that I'm trying to implement, but I'm facing some challenges. I've been experimenting with the code but I feel like there are part ...

Javascript auto submission fails to execute following the completion of the printer script

As someone new to javascript, I have a question. I have a function called sendToQuickPrinter() that prints correctly, but after it finishes executing, I need to automatically submit a form to return to my "cart.php" page. I feel like I'm almost there, ...

Steps to generate a fresh array from a given array of objects in JavaScript

Looking to transform an existing array into a new array of objects in Vue.js. Here's the initial array : import { ref } from 'vue'; const base_array = ref([ {id: 1, name: Pill, timing: [morning, noon, evening, night]}, {id: 2, name: Ta ...

Creating a complex array structure using checkbox inputs within an Angular application

In my Angular application, I have a list of checkboxes that are dynamically generated using nested ng-repeat: <div ng-repeat="type in boundaryPartners"> <div class="row" ng-show="showBPtype[$index]"> <div class="col-xs-12"> ...

Error: null value cannot be scrolled into view - testing with react, jest, and enzyme

Utilizing react version 16.3.1, jest version 16.3.1, and enzyme version 3.3.0. Inside my React Class component, I have implemented a react ref to ensure that upon mounting the component, the browser scrolls back to the top of the page. class PageView ext ...

Python Automation with Selenium (Locating elements using CSS selectors)

Is it possible to select and access the first element of an array using a CSS selector in Python? For instance: css=('.od-FieldEditor-fieldTitle.ms-Label.is-required') generates an array of 6 labels. I am interested in accessing the innerText a ...

JSON does not send information to the specified web address

Attempting to send some data to the following URL: " $(function() { var frm = $(document.myform); var data = "?lm_po_id=154668&authentication=ThisisAuth&description=ThisIsDesc";//JSON.stringify(frm.serializeArray()); ...

What is the best method for scrolling down a JavaScript table using Selenium in Python?

My dynamic table is created using JavaScript. When the page loads, only the first elements are visible in the source code. This means that when I try to scrape values from the table, only the initial parts are retrieved. Before scraping, I need to scroll ...

How to Effortlessly Populate Cascading Dropdowns in ASP.Net MVC 5 using a Reusable

I am currently working on an ASP.Net MVC 5 application that has multiple edit pages. Each edit page consists of various input elements such as textboxes, checkboxes, and dropdowns. I want to implement a functionality where the values of one dropdown are ch ...

Retrieving ng-pattern as a variable from a service

Hey there! I'm currently working on an application that requires extensive form validation across multiple pages. To streamline this process, I am attempting to extract validation patterns from a service used among the controllers. However, I've ...

After deploying DRF, the CSS in Django admin is not displaying

After developing a web application using Django Rest Framework and React, I faced an issue during deployment on IIS. While the deployment is successful, I encountered a problem with the Django Admin where the styles were not displaying properly. This led t ...

Tips for changing the appearance of an entire table by overriding the table tr:nth-child styling

In the CSS code below, I currently alternate background colors for table lines by default and can specify individual rows to not alternate. Is there a way to implement this at the table level instead of per row? Essentially, I want to define something at ...

Tips on reversing a numeric value with scientific notation in nodeJS

Exploring the optimal method to reverse an integer (positive and negative) in NodeJS 12 without the need to convert the number to a string. This solution should also accommodate numbers written in scientific notation such as 1e+10, which represents 10000 ...

Firefox is not allowing the form to be submitted at this time

My form is functioning correctly on Chrome and Safari, but not on Firefox. Solution Attempt #1 <form id="subscribe-form" class="footer-sign-up" action="/subscribe" method="POST"> <input type="text&q ...

How to modify a variable within the "beforeSend: function()" using Ajax and jQuery

I am facing an issue with my ajax contact form. The beforeSend function is supposed to validate the inputs and pass the parameters to a PHP file for sending emails. However, I always receive false instead of true even when the inputs are valid. I suspect ...

Form submission issue with dynamically added input fields within a modal

I'm facing a problem where dynamically added input fields in a modal are not being included when the form is submitted. The scenario involves a modal with a form, where input fields are added dynamically upon clicking an "Add" button. Each input fiel ...

Checking the validity of date inputs - microservice for timestamps

I'm encountering an issue while attempting to validate my date input. I've tried using moment js, but it seems there's a problem. The error message "date invalid" keeps popping up! Here is the code snippet: app.get("/api/timestamp/:date_s ...