eliminate any following divs that come after a specific child element

I have a similar structure like the following :

<div>
     <div class="productPage"></div>       
     <div>is hidden</div>  // ***this content will be hidden
</div>

// *** this one will not become hidden.
<div>not hidden..</div>

using this approach:

   $( ".productPage").nextAll().addClass( "hidden" );

This code snippet will only hide the specific content I identified, which are the children of the same parent element. What I am looking to achieve is hiding every single thing that comes after productPage.

Answer №1

Make sure to visit the parent element and target the following divs.

$(".productPage").nextAll().addClass("hidden");
$(".productPage").parents("div").eq(0).nextAll().addClass("hidden");
.hidden {
  display:none;
}
<div>
  <div class="productPage"></div>
  <div>is hidden</div> <!-- this content will be hidden  -->
</div>

<!-- this one will not become hidden. -->
<div>not hidden..</div>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

Answer №2

If you want to hide elements following the .productPage that share the same parent, you can utilize the Next Siblings Selector ~

This method will target all elements that come after the .productPage and have the same parent as well as match the div selector

$(".productPage ~ div").addClass("hidden");
.hidden {
  display:none;
}
<div>
  <div class="productPage"></div>
  <div>is hidden</div> <!-- this content will be hidden  -->
</div>

<!-- this one will not become hidden. -->
<div>not hidden..</div>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

Answer №3

This method involves a combination of JavaScript techniques.

Instructions

1. Identify all HTML nodes on the page.
2. Locate nodes with the class name 'productPage'.
3. Once the class is found, hide the following nodes by adding the hidden class to them.

By following these steps, all nodes belonging to a specific class will be removed from the DOM structure, regardless of their position in the hierarchy.

$(document).ready(function() {
  $('button').click(function() {
    const allNodes = $('*'); // Get all HTML nodes
    let itemIndex = null;
    allNodes.map((index, node) => {
      node.className &&
      node.className.indexOf('productPage') > -1 &&
      itemIndex === null
        ? (itemIndex = index)
        : itemIndex !== null
        ? (node.className += ' hidden')
        : null;
    });
  });
});
.hidden {
  visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div>
  <div>
    <div>Will Remain Visible</div>
    <div class="productPage">Product Page</div>
    <div>will be hidden</div>
  </div>
</div>
<div>This content will not be hidden.</div>
<button>Click Me</button>

I trust this meets your requirements.

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

Can child elements be protected from deletion when their parent is set to contentEditable?

When a website element has the attribute contentEditable, its child elements can be removed. However, if one of those child elements is not set to be contentEditable, then the content within it cannot be edited but the entire element can still be deleted. ...

Mongoose JS is unable to display the query value in the output

Is there a way to use mongoose js to create a collection of kittens with specific attributes like {name: "mike"}? Once this document is created, I need to be able to view its value. I've attempted to write the following code: However, I've enco ...

Filling Out HTML Form Using Ajax, PHP, and MySQL

I am in the process of creating a form that will be filled using ajax after a select box is chosen. I would greatly appreciate your advice and suggestions on how to improve it. Here is the script I am working with: `[HTML] AND [AJAX]` <script typ ...

Getting the full referrer URL can be achieved by using various methods depending

I am currently working with ASP.Net. My goal is to retrieve the complete referrer URL when visitors arrive at my website from: https://www.google.co.il/webhp?sourceid=chrome-instant&rlz=1C1CHEU_iwIL457IL457&ion=1&espv=2&ie=UTF-8#q=%D7%90 ...

Tips for restricting the preloader display to once per session

My website features a preloader on every page. <div id="preloader" > <div id="status"></div> <div id="statustext">some text</div> </div> This preloader is activated using the following jQuery code: //<![CDATA[ var ...

Guide to displaying a loading message while performing a synchronous AJAX request in a web browser

Is there a way to display a waiting message during a synchronous AJAX call in the browser? I attempted to use the code below, but even after turning off the web server, the "Saving" message did not appear. After some time, only an error event from the AJA ...

What causes a user to log out when the page is refreshed in a React/Redux application?

Each time the page is reloaded in my React/Redux application, the user gets logged out, even though I have stored the token in localStorage. There seems to be an error somewhere. The token should ideally be saved when the user logs in and not lost upon rel ...

Capturing Key Events on Canvas in Vue.js

When using Vue 2.5, I encountered an issue with a canvas element that has a key event listener: <template> <canvas v-on:keyup.esc="abortThing"></canvas> </template> <script> export default { methods: { abortTh ...

A guide on extracting JSON data from a script tag using Cheerio

I am in the process of extracting metadata from various websites. While utilizing Cheerio to retrieve elements like $('meta[property="article:published_time"]').attr('content') works smoothly for most sites, there are some whe ...

Boost Script - when you move your mouse

Seeking assistance and truly grateful for any help! I came across an image magnifier on Dynamic Drive, but it's not exactly what I need. It's great except for one thing - I don't want the user to click on the image to view it, I want them t ...

"Troubleshooting issue: jQuery AJAX encountering problems with parsing JSON

I recently came across a Uncaught SyntaxError: Unexpected end of input error in my code. var dataURL = "LineChartController?tp=" + tpAtt + "&dept=" + dept + "&date=" + dateMY; alert(dataURL); var JSONdata = jQuery.aja ...

Activate the sliding animation for closing the modal window

I have successfully implemented a modal using a combination of html, css, and JavaScript. The code snippets are provided below for reference. One noticeable feature is that the modal window opens with a sliding animation effect from the top. However, I a ...

Why do elements align horizontally in a div even when I specify it to display as a block?

My understanding is that display: block is the default setting. However, even after specifically setting display: block, my div was still aligning items horizontally. The only solution I found was to use: display: flex; flex-direction: column; Any insight ...

Reading a file after it has been successfully uploaded to a server

Implemented HTML code to receive a file and send it to the server. However, I prefer to keep the data on the client side instead of the server. How can I achieve this while still being able to access the data? The solution needs to be compatible with IE8 o ...

Cease the use of bi-directional data binding on an Angular directive

One way I've been attempting to send information to a directive is through the following setup: <ui-message data="{{app}}"></ui-message> In my controller, this is how I define it: app.controller("testCtrl", function($scope) { $scope.a ...

Submitting an intricate item to a WCF REST API using JQuery

Currently, I am attempting to send a complex object to my WCF REST service. Utilizing this method seems to be the most straightforward way to upload a Stream type object along with other parameters to an endpoint simultaneously. Service: [OperationContra ...

Using Object Values and Subvalues to Assign Element Attributes in jQuery

I have a weekly schedule that I update regularly using a static table layout: <table> <tr class="live gm fsp"> <td>Oct. 7</td> <td>12:30 pm</td> <td class="prog">Show 1</td> <td>Team ...

Combining Rails 4 with coffeescript while encountering an issue with the jQuery sortable detatch functionality

Currently, I am using Ruby on Rails 4 along with the jquery-ui-rails gem. Within my application, there are certain lists that have a sortable jQuery function implemented. $ -> $('#projects').sortable handle: '.handle' ...

Strange occurrence with getBoundingClientRect() function and F5 refresh, what could be causing this odd behavior?

Apologies for the lengthy code, I have stripped it down multiple times to make it stand-alone. Codepen won't be helpful in this case. You can simply copy and paste the code into an HTML file to see how it behaves. <!DOCTYPE html> <html> &l ...

What could be the reason for the jQuery not displaying JSON data in the console log?

When I put this code into a file named test.html: <html> <head> <title>Test</title> </head> <body> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"& ...