Hard-won Javascript/JQuery wisdom and useful (benign) hacks

Last updated:

invisible (display:none) elements

invisible (display:none) elements cause all sorts of trouble: sometimes (always?) you can't interact with an element if it's invisible.


if you have a piece of code that doesn't work no matter what, try wrapping your code in a setTimeout() call and test if it still doesn't work. A few microseconds can make a lot of difference to javascript but not much difference to human eyes.

selectors/selecting DOM elements

getting the selected text of a dropDownBox:


jQuery get selected text from dropdownlist at stackoverflow

html button default type is submit!

not strictly javascript or jquery but, since we deal with forms all the time, it's good to know that if you don't define a <button> type, it will default to submit and cause any forms to submit! this has caused me some hard-to-debug problems, even though I already knew about it, so I figure it's worth mentioning.

get does not return a jQuery object, use eq instead

if, for instance, you have a selector that returns many elements, you probably want to use jquery's eq(index) to fetch one of the elements because if you just use get(index) you'll still get the element but it won't be a jquery object so you won't be able to do anything with it.

So, assuming you have a document with two <div>s:

var elements = $("div"); //will yield a list of the two divs
elements.eq(1).html("foo");//works and sets the content of the second div
elements.get(1).html("foo"); does not work and an error is thrown


use obj1.hasOwnProperty('attribute1') to find out whether obj1 has an attribute named attr1

scoped jQuery queries

search for an element inside this element only:


this allows you to perform queries but give as container another element.

reading pure text form the server

Any text sent directly from the server (for example, via PHP echo function) maybe or may not reach the browser exactly as it was sent. Therefore, if you are writing, for instance, a $.post jQuery ajax request, make sure your check first whether the data has arrived exactly like it arrived (i.e. no \n before or after the actual text or anything like that). I recommend you check pure text send from the browser using the String.match javascript function, for example:

        param: 'some_value'
        }else if(data.match(/failure/)){
            //neither one nor the other, do something like send an alert()

Dialogue & Discussion