jQuery Tips & FAQ

How to define multiple CSS rules / properties in jQuery?

The simplest way to define a CSS rule in jQuery might be: $(".sth").css("color", "#f00"); To define more than one CSS rule in a single jQuery line: $(".sth").css("color", "#f00").css("font-style", "italic").css("text-decoration", "underline"); Which simply doesn’t look that good, especially if you intend to add more. A better way to specify multiple CSS rules or properties with jQuery …

How to define multiple CSS rules / properties in jQuery? Read More »

jQuery: Protecting or hiding variables / functions in a specific local scope

As everyone who’s well trained in software engineering would agree, that one of the principle of writing predictable code is to separate and hide something within only the scope that it’s needed. Controlled access to and from the outside world brings predictability and accountability of your code thus better debugging. In jQuery, you need constantly …

jQuery: Protecting or hiding variables / functions in a specific local scope Read More »

jQuery: Get the text and value of the selected option of HTML select element

For instance, there’s a HTML select element identified by the ID #title, and after the user has selected one of the options, you want to get the text and value of the selected option. <select id="title"> <option value="1">Mr</option> <option value="2">Mrs</option> <option value="3">Miss</option> </select> Now that the user has selected the 2nd option: Mrs. To get …

jQuery: Get the text and value of the selected option of HTML select element Read More »

jQuery: How to check if an element has a particular class

To know whether a class exists on an element with jQuery, you need a simple test method: is(). For example, to test if an element #elm has the class ‘first’: if ($(#elm).is(‘.first’)) { //#elm has the class } else { //#elm doesn’t have the class } jQuery is() is the function that checks if any …

jQuery: How to check if an element has a particular class Read More »

jQuery: How to test or check whether an element exists

.length property in JavaScript returns the length or number of elements inside an array or the string length. While jQuery selector mechanism $(“elm”) returns an array of DOM objects (such as elements), you can also get the number of the length of the returned objects array by: $("#some").length To check the existence of the element, …

jQuery: How to test or check whether an element exists Read More »

jQuery: Selecting elements with uncommon / special characters in ID or class name

HTML generated by some CMS or frameworks include elements with rather uncommon characters in ID or class names. For example, some may have special characters such as ‘.’ or ‘[..]’ in the ID or Class. To work around this, a selector in jQuery should be written this way: $(“$some.id”) // won’t work for ID: some.id …

jQuery: Selecting elements with uncommon / special characters in ID or class name Read More »

Scroll to Top