Assign a class to the child element if it shares a numerical class with its parent

My goal is to apply a specific class to a child element if it shares the same numeric class as its parent. If the child does not have the same numeric class as the parent, then I want to remove that child element altogether. However, I am encountering an error message that says: "Cannot read property '1' of null."

jQuery( 'article' ).each( function() {
 var parent_id = jQuery(this).attr('class').match(/post-(\d+)/)[1];
  var child_id = jQuery(this).children('div').attr('class').match(/post-(\d+)/)[1];
  
  if ( child_id == parent_id ) {
  jQuery(this).children('div').addClass('visible');
}
              });
article {
 width:200px;
 height:200px;
 background: red;
 margin:20px;
}
.inner {
 width:100px;
 height:100px;
 margin:20px;
 background: black;
}
<article class="post-45">
  <div class="post-55 inner"></div>
  <div class="post-44 inner"></div>
  <div class="post-45 inner"></div>
</article>
<article class="post-55">
  <div class="post-34 inner"></div>
  <div class="post-55 inner"></div>
  <div class="post-45 inner"></div>
</article>
<article class="post-34">
  <div class="post-34 inner"></div>
  <div class="post-45 inner"></div>
  <div class="post-55 inner"></div>
</article>

Answer №1

To achieve the desired result, you can implement an each() function specifically for the divs within each article:

jQuery('article').each(function() {
  var parent_id = jQuery(this).attr('class').match(/post-(\d+)/)[1];
  jQuery(this).children('div').each(function() {
    var child_id = jQuery(this).attr('class').match(/post-(\d+)/)[1];
    if (child_id == parent_id) {
      jQuery(this).addClass('visible');
    }
  });
});
article {
 width:200px;
 height:200px;
 background: red;
 margin:20px;
}
.inner {
 width:100px;
 height:100px;
 margin:20px;
 background: black;
 display:none;
}
.visible {
  display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article class="post-45">
  <div class="post-55 inner"></div>
  <div class="post-44 inner"></div>
  <div class="post-45 inner"></div>
</article>
<article class="post-55">
  <div class="post-34 inner"></div>
  <div class="post-55 inner"></div>
  <div class="post-45 inner"></div>
</article>
<article class="post-34">
  <div class="post-34 inner"></div>
  <div class="post-45 inner"></div>
  <div class="post-55 inner"></div>
</article>

Answer №2

To enhance the functionality, a more efficient approach would involve extracting the class attribute of each article by utilizing .attr(). Subsequently, apply .find() within the .each() loop to target the specific child element based on the retrieved class value. Here is an example demonstrating this process:

$( 'article' ).each(function(i, el){
  let elClass = $(el).attr('class');
  $(el).find(`.${elClass}`).addClass('visibile');
});
article {
 width:200px;
 height:200px;
 background: red;
 margin:20px;
}
.inner {
 width:100px;
 height:100px;
 margin:20px;
 background: black;
 display:none;
}
.visibile {
  display: block;
}
<article class="post-45">
  <div class="post-55 inner"></div>
  <div class="post-44 inner"></div>
  <div class="post-45 inner"></div>
</article>
<article class="post-55">
  <div class="post-34 inner"></div>
  <div class="post-55 inner"></div>
  <div class="post-45 inner"></div>
</article>
<article class="post-34">
  <div class="post-34 inner"></div>
  <div class="post-45 inner"></div>
  <div class="post-55 inner"></div>
</article>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

Issues with Adsense on a PHP website

I am experiencing a challenge with my Adsense account, as it is working on one site but not on another one. The non-functioning site is written in PHP, and despite trying different variations of the code, I am unable to display the ads successfully. The ...

Creating a dynamic Bootstrap carousel with a fixed hero header text inside a designated container - here's how!

I am currently working on a project to develop a responsive Bootstrap slider with a fixed hero header that remains consistent while the slider images change. The hero header needs to be aligned to the left within a responsive Bootstrap container and center ...

Using jquery, you can easily toggle the functionality of asp:validators by enabling

I am currently collaborating with a wizard that allows users to sign up. Within this wizard, there is an asp:RadioButtonList featuring two options, and some of the input fields within the wizard dynamically change based on the selected radiobutton. Each fi ...

Error encountered: SyntaxError - Missing semicolon before statement in AJAX call while processing JSON data

I am currently in the process of making a cross domain JSONP call utilizing this code snippet: jQuery.ajax({ async: true, url: 'http://mnews.hostoi.com/test.json', dataType: 'jsonp', method: "GET&quo ...

Crafting a callback function similar to using the jQuery click event handler

When utilizing jQuery, callbacks can be implemented in the following manner: $('#btn').on('click', function() { // code }); Is it possible to create something similar with a structure like this? foo.on('bar', function() { ...

Creating dynamic drop-down menus using PHP, HTML, JavaScript, and MySQL

I need help with a form where users are required to select departments and based on that, the corresponding defect fields should populate with matching defects. Currently, when I try removing Defect 4, Defect 3 works; remove 4 & 3, then 2 works and so fo ...

JavaScript: Retrieve values from individual textareas with identical class names

Imagine you have multiple text areas like the ones below: <textarea class='save'></textarea> <textarea class='save'></textarea> <textarea class='save'></textarea> All of them are assigned ...

Are there any alternative methods to elegantly organize a form within a table other than the one showcased here? My form consists of varying numbers of

Within the initial row, I have incorporated four columns, while rows 2-4 contain two columns each to enhance the formatting. I am seeking a more elegant approach to address this issue and avoid triggering the validation warning. This task pertains to a s ...

Giant Slide - navigate directly to a particular slide using a link

Hey there, I am currently working on incorporating the Superslide slider for fullscreen images in my website. My goal is to have a mostly text-free site where users can navigate through the images using the main menu or jump to a specific image within the ...

Managing the hierarchy of controllers in CodeIgniter

I've been looking everywhere to find an example in Codeigniter on how to build a tree structure like the one below. If anyone can provide me with some assistance, it would be greatly appreciated. Specifically, when I click on child node 2, I want to ...

Using an image tag within a button element causes functionality issues with JavaScript on Chrome

Can anyone help me figure out why my button with an image isn't toggling a div's class in Chrome? It works fine in Firefox. Here is the codepen link for reference: https://codepen.io/luansergiomattos/pen/zydWyM This is the HTML code: <div cl ...

Creating an array object in JavaScript is a straightforward process that involves using the array

Looking to achieve the following object list structure: myObj = {"foo":[1,2,3,4], "bar":[3,5,7,8]} Initial attempt was unsuccessful: var myObj = new Object(); myObj["foo"].push(1) myObj["foo"].push(2) #...etc Seeking guidance on the correct m ...

What is the best way to retrieve the checkbox value using AJAX/jQuery with a Spring form?

My form contains a group of checkboxes identified by the path deliveryStatus, like so: <form:checkbox path="deliveryStatus" value="notDelivered"/> <form:checkbox path="deliveryStatus" value="delivered"/> I came across two helpful examples: E ...

Clear your browser cache upon opening it

My website utilizes jquery.ajax for various actions. However, when I initiate an ajax action, close the browser, and reopen it, I do not see the changes made by ajax. How can I prompt the browser to refresh the page upon reopening? ...

What is the best way to include interactive text on an image?

Just starting to learn html and could use some quick guidance. I have this image here: https://i.sstatic.net/kBJEk.png I would like to place clickable text on the image that links to different pages when clicked, similar to this example: https://i.sstatic ...

Can you switch between displaying and concealing a dropdown in the same location based on chosen values?

I have four dropdowns listed, but I only want to display one at a time. Depending on the selected values, when I try to show a dropdown, it does not replace the current one; instead, it just appears next to the existing dropdown. Is there a way to keep th ...

Tips for executing a jQuery function on multiple sets of elements

Currently, I have a list with all items sharing the same class name. There is a jQuery plugin that identifies the tallest element and sets the height of all list items to match the tallest one. My goal is to run this method for each UL group individually. ...

Ways to modify the color of a selected dropdown in a navigation bar

Every time I click on the dropdown menu, it gets highlighted in blue. Is there a way to change this using Bootstrap or by adjusting my CSS? I've already attempted changing the color with this CSS element: .dropdown-item.active, .dropdown-item:active ...

Unexpected issue encountered while working with json, ajax, and jQuery

Here's the code snippet that I'm working with: $.ajax({type: 'get', mode: 'abort', dataType: 'json', url: 'http://localhost/1.php', data: {}, success: function(res){ alert(res); }, time ...

What is the best way to implement a dropdown in MUI and React that displays functional components as items?

Here is a list of dummy components: const OwnerList = () => { return ( <Box sx={{ display: 'flex', }} className="owner-container" > <Avatar src='https://hips.hearstapps.com/hmg- ...