The Document Object Model is an API which allows developers to access, read, and modify the content of a web page. In this article, I'm going to show you 10+ extremely useful code snippets to manipulate the DOM using jQuery.

Add a CSS class to a specific element

A very clean way to change an element look and feel is to add a css class, instead of adding inline styles. Using jQuery, this is pretty easy to do:

$('#myelement').addClass('myclass');

Removing a CSS class from a specific element

It’s great to be able to add some CSS classes, but we also need to know how to remove unwanted classes. The following line of code will do that:

$('#myelement').removeClass('myclass');

Check if a specific element has a CSS class

If your application or site is frequently adding and removing classes to a particular element, it can be very useful to be able to check out if an element has a certain CSS class.

$(id).hasClass(class)

Switch CSS using jQuery

As we saw with the previous examples, adding or removing css styles to an element is very simple using jQuery. But what if you want to completely remove the document css file and attach a new stylesheet? Good news, it is extremely simple as well, as shown in the following example:

$('link[media='screen']').attr('href', 'Alternative.css');

Source: http://addyosmani.com/blog/50-jquery-snippets-for-developers/

Append HTML to an element

When you need to append some html to an element, the append() method is a life saver:

$('#lal').append('sometext');

Check if an element exists

When working with Javascript, we often need to check if an element exists or not. Using jQuery and the length property, it is very simple to do: If length == 0, no elements are used on the page. Otherwise, some are used.

if ($('img').length) {
    log('We found img elements on the page using "img"');
} else {
    log('No img elements found');
}

Source: http://jqueryfordesigners.com/element-exists/

Get the parent element of an element

When working with the DOM, you may need to know which element is the direct parent of another element. The closest() method will let you know:

var id = $("button").closest("div").attr("id");

Source: http://stackoverflow.com/questions/545978/finding-the-id-of-a-parent-div-using-jquery

Get element siblings

The siblings() method is a very handy tool to get siblings of an element. As shown below, using this method is extremely simple:

$("div").siblings()

Remove an option from a select list

When working with select lists, you may want to update the content according to the user actions. To remove an option from a select list, the following code will do the trick:

$("#selectList option[value='2']").remove();

Source: http://calisza.wordpress.com/2009/03/29/6-jquery-snippets-you-can-use-to-manipulate-select-inputs/

Get the selected option as text

Extremely useful when you need to quickly check out what a visitor selected from your select list.

$('#selectList :selected').text();

Apply a “zebra” effect on tables

When using tables, it is a good idea, for better readability, to give a different style to one line out of two. Using jQuery, this can be done easily, without any additional html markup.

$("tr:odd").addClass("odd");

Source: http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/

Count children of an element

If you’d like to count how many div elements are children of #foo, the following line will let you know. Simple and efficient!

$("#foo > div").length

Source: http://tympanus.net/codrops/2010/01/05/some-useful-javascript-jquery-snippets/

 

22 Comments

  1. Posted April 20, 2010 at 10:03 am | Permalink

    I use almost everyday the addClass and removeClass. Playing with classes it’s once the best things in jQuery.

    Regards

    • Posted April 22, 2010 at 9:13 am | Permalink

      Hi quicoto,
      I like to play with jQuery too.
      Most of the time they are just crap but may be after learning a bit I will improve.

  2. Ricardo Verhaeg
    Posted April 20, 2010 at 10:09 am | Permalink

    Thanks.. I really find useful about the closest() I was using the parents() before but it was not what i expected!
    Very nice tips also!
    thanks

    • Posted May 12, 2010 at 8:40 am | Permalink

      I this they do what they should do … closest … finds the closets thing of something.

      While parents only looks at the parent.

      mvh

  3. Thomas
    Posted April 20, 2010 at 10:20 am | Permalink

    “When working with the DOM, you may need to know which element is the direct parent of another element. The closest() method will let you know:”

    You can get the direct parent with $(’#element’).parent();
    closest() returns the next ancestor matching the given selector, which is not necessarily the direct parent.

  4. Posted April 20, 2010 at 10:30 am | Permalink

    That’s a supercool post Jean. Bookmarked cause it’d save a lot of headaches, especially “Add a CSS class to a specific element” and “Apply a “zebra” effect on tables”. Kudos.

    • Posted April 22, 2010 at 1:27 pm | Permalink

      For this “zebra” effect you might use pure CSS, no jQuery is needed.
      The :nth-child()-selector does this for you, e.g.:
      li:nth-child(odd) {} does the “zebra” effect which is described above on a list, this also works with tables.

      • Posted April 22, 2010 at 1:42 pm | Permalink

        Definitely, but if you want your code to be compatible with IE the jQuery solution is the way to go.

  5. Posted April 20, 2010 at 11:52 am | Permalink

    wow….great stuff….thnx for sharing such useful info with us..

  6. brian
    Posted April 21, 2010 at 4:48 pm | Permalink

    what a useless bullshit. try the api next time. shame on sm for linking

  7. Posted April 22, 2010 at 4:18 am | Permalink

    Why use closest for finding parent when there is a parent() function?

    var id = $(”button”).parent().attr(”id”);

    • Ricardo Verhaeg
      Posted April 22, 2010 at 9:51 am | Permalink

      From docs.jquery.com:

      “The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:
      .closest()
      Begins with the current element
      Travels up the DOM tree until it finds a match for the supplied selector
      The returned jQuery object contains zero or one element

      .parent()
      Begins with the parent element
      Travels up the DOM tree to the document’s root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
      The returned jQuery object contains zero, one, or multiple elements”

      So the basic difference is that with parent you may find multiple parents and with closest you get only the first found parent.

      • Posted April 25, 2010 at 2:42 pm | Permalink

        You are describing parents, not parent.

        To understand (I hope I can write some code here…):


        <div id="level-one" class="foo bar">
        <div id="level-two" class="foo">
        <div id="target">
        </div>
        </div>
        </div>


        $("#target").parents(".foo") // Returns #level-one and #level-two
        $("#target").closest(".foo") // Returns #level-two
        $("#target").closest(".bar") // Returns #level-one
        $("#target").parent(".foo") // Returns #level-two
        $("#target").parent(".bar") // Returns nothing

  8. Posted April 22, 2010 at 9:29 am | Permalink

    Ten very helpful tools to integrate jQuery into the Document Object Model. Thanks.

  9. Posted April 22, 2010 at 11:48 am | Permalink

    Why use abutting for award ancestor back there is a parent() function?

  10. Posted April 25, 2010 at 3:05 pm | Permalink

    Great selection! Thank you for the cheatsheet…

  11. Posted May 7, 2010 at 10:35 am | Permalink

    Great post, look like really useful snippets of code. Can’t wait to try them!
    Thanks for sharing.

  12. Posted May 20, 2010 at 11:09 am | Permalink

    Check if an element exists. I use this every my project. It example in this article is very usfull.

  13. Posted June 15, 2010 at 10:05 am | Permalink

    Great post. Book marked!

  14. Posted July 26, 2010 at 12:03 pm | Permalink

    Really useful list, one to bookmark. Thanks Jean-Baptiste!

6 Trackbacks

  1. By uberVU - social comments on April 20, 2010 at 10:08 am

    Social comments and analytics for this post…

    This post was mentioned on Twitter by jmgall: Manipulating the DOM with jQuery: 10+ useful code snippets http://goo.gl/fb/T9mSO CatsWhoCode.com #webdevelopment…

  2. [...] link: Manipulating the DOM with jQuery: 10+ useful code snippets If you enjoyed this article please consider sharing [...]

  3. [...] avril 2010 par Toto Manipulating the DOM with jQuery: 10+ useful code snippets: [...]

  4. [...] A very clean way to change an element look and feel is to add a css class, instead of adding inline styles. Using jQuery, this is pretty easy to do: view source [...]

  5. [...] full post on CatsWhoCode.com Tags: code, Jquery, Manipulating, snippets, useful Share this [...]

  6. By Napi okosságok – 2010/04/22 | Yloz féle zacc on April 22, 2010 at 5:54 pm

    [...] Manipulating the DOM with jQuery: 10+ useful code snippets [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting

  • Smashing Network
  • Hosted by VPS.net and Akamai CDN
WordPress Appliance - Powered by TurnKey Linux