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.)

thePixelPixie.com - WordPress boutique

Subscribe and receive my FREE eBook


4 MISTAKES You’re Making on Your Website that are Costing You MONEY!

  • This field is for validation purposes and should be left unchanged.

The Author

Save

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Ready to chat about how ThePixelPixie can help?