I’m not great at updates to my own site, but I do want to keep track of snippets I end up using here and there.
First up is a little js I wrote yesterday to solve a quick issue on my employer’s website. We needed a way to target a card on a page that did not have any unique classes from all the others. My solution was to detect if a card had certain text in it’s href link, then apply a new class to it’s specific parent div. From there, it was a simple matter of writing the CSS attributes to go with that new class. It worked great!
jQuery(document).ready(function($) {
$('a[href^="/specific_path_i_was_looking_for"]').each(function() {
$(this).closest('.parent-div-name').addClass('new-class');
})
});
This could also easily done by looking for a unique id attribute:
jQuery(document).ready(function($) {
$('a.existing-class-name[id*="unique-string"]').each(function() {
$(this).closest('.parent-div-name').addClass('new-class');
})
});
A few keywords for the aggregators in case this snippet is useful for someone else looking for this sort of thing: js, jquery, div contains, add class to parent, css, html,find specific attribute then add class to parent div (note, I’m not sure adding these is actually helpful, but I suppose I’ll find out over time! They might be more helpful if I did like so many bloggers and wrote a whole long…thing…before I got to my actual point. But that ain’t me. Sorry.)