How to Visually See What Your jQuery Selection is Selecting


How to Visually See What Your jQuery Selection is Selecting

I was recently working on form validation and wanted to mark a.form-group as successful if it contained a particular icon inside the label. The icon was set using PHP depending if the data existed in the database.

I was writing .prev() and .parent() to try and select the wrapping .form-group but it wasn’t working and I wanted to see visually what my jQuery selection was doing. Then I remembered a CSS trick I have used with CSS to wrap all block-level elements with a border to see how it is used in a layout.

* {border:1px solid red;}

So what I decided to do was create a custom jQuery function I could reuse when I wanted to test my selection. Once I know I am targeting the right element I can continue writing the rest of my code.

Inspect element selection with jQuery custom function

  // create a custom jQuery function to outline element
  $.fn.inspect = function() {
    $(this).css("border", "2px dashed red");
  }; 
  
  // Test your selection using this function
  $('.list-group li:nth-child(3)').inspect();

View Demo

 


About the Author

Jacob Lett (Jake) is the founder of Bootstrap Creative, a B2B marketing consultancy specializing in manufacturers and industrial companies. A HubSpot-certified CMS developer, SEO, Answer Engine Optimization (AEO), and RevOps professional, he helps B2B companies improve their websites, search visibility, HubSpot systems, and Google Ads campaigns to generate more qualified leads and RFQs. With over a decade of hands-on experience, he acts as a direct partner for companies seeking measurable ROI from their marketing investment.



Related posts
Category: Code Snippets / Tutorials

Tags: ,

| Read My Editorial Policy

Want to Get Email Updates of New Articles?

Join My Email Newsletter