This will be a growing list of jQury, maybe even general JavaScript Snippets that I use a lot and always forget.
# Add/Remove a class jQuery
Add a class to a element
jQuery(‘selector’).addClass(‘active’);
Remove class from an element
$( "p" ).removeClass( "myClass yourClass" )
# Find the html <a>
Element with href that contain a certain string
Sometimes you need to find in your web page a anchor element with a specific string in it’s href
this is example of find the a tag with href that contains “vc” var and adds a class to it’s
parent element.
jQuery('#menu-vendor-team-categories a[href*=“'+vc+'"]').parent().addClass('active');
Some of the selector stuff you can use, based on your needs:
Selector documentation can be found at:
For Example:
=
– find a string that is exactly equal.
!=
– find a string that is not equal.
^=
– find a string that starts with.
$=
– find a string that ends with.
*=
– find a string that contains.
~=
– find a strings that contain this word.
|=
– find a string that starts with a prefix (|=
“prefix” matches “prefix-…”).
# Prevent Default
General Javascript snippet.
Stop the normal behavior of this element click event and do what i want.
Can be applied with .on click – so that on click it will prevent default behavior and do as you please
jQuery( ‘.#myElement' ).click(function( event ) { event.preventDefault(); // do as you please here ! } });
# Get Href of element (Guess it’s good for getting more things)
href now contains the href string of this element. (if you got stupid or something):
var href = jQuery(this).attr('href');