Skip to content

Instantly share code, notes, and snippets.

@tomleo
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomleo/3bc3249d8b2e472c924b to your computer and use it in GitHub Desktop.
Save tomleo/3bc3249d8b2e472c924b to your computer and use it in GitHub Desktop.
DOM manipulation gotchas and things I've learned

innerHTML is a lie

If you want the value of a form field such as a text area you might think $('textarea').html() would return what you expected. If you have not changed the text in that textarea, then your assertion is correct. However if you do change the text in the text area, then call $('textarea').html() again, you will notice that the returned value did not change.

This is not a bug in jQuery, but just a subtle gotcha in the way the DOM works. The solution is to get the DOM elements value via $('textarea').val().1

Bubble Bubble less toil and trouble

Suppose you have the following markup

<div id="poster">
    <p id="info"></p>
</div>

And you attach an evenet listener to $('#info'). If you change the innerHTML of poster, then the paragraph (even if it has the same id) does not have an event listener attached to it.

Now events such as click are still being triggered when you click on the new paragraph element. So rather than attempting to attach event listeners to the new element after it has been created you can simply listen for the event as it bubbles up the DOM. If you know that $('poster') will never change, you can attach the event listener to that element. This is called event delegation and it's the bee's knees.

In jQuery it would look something like this

$('#poster').on('click', '#info', function() {
    //Do some cool things
});

then-ability

Asynchronous calls are non-blocking, if you wish for one function to happen after the asynchronous function returned you implement a callback function. However if you need to do multiple asynchronous calls that require other asynchronous calls you will have a large nest of callback functions.

A nice design pattern to make this type of code easier to read is called Promise/A+2

The library I have found most useful is called q3 one nice thing about q is it's ability to wrap jQuery functions so that the returned promise has a nicer API.

Promises can also be used for more than just ajax calls. For example you could do something like this

$('#my-div').html('<p>Something Completly Different</p>').promise().done(function(){
    $('#my-div').find('p').on('click', function() {
        alert("HI!");
    });
});

** A better way to attach event listeners to elements that have not been created yet would be via event delegation **


  1. http://stackoverflow.com/a/6004028/465270

  2. https://promisesaplus.com/

  3. http://documentup.com/kriskowal/q/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment