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>