Basic DOM manipulation with JQuery – I

This was originally published on Oct-25-2013

I often find myself wanting to do simple things such as creating a reusable navigation menu across multiple views without having to duplicate the html for each. For example, if we have the following navigation items, About, Contact, and Home; and we are on the Home page, I would want the home link to be disabled and the others enabled. Similarly when we are on the About page, I would want the About link to be disabled and Home and Contact to be enabled… you get the idea.

In order to do this, what I did was

  1. Create a standard layout template with all three links
  2. Create CSS classes for enabling and disabling,
  3. Identify the link that needs to be disabled (maybe by passing in a variable from the controller)
  4. Identify the link in the DOM using Jscript
  5. Set the appropriate Class using Jscript.

Of these steps, the common theme is

  1. Identify an entity in the DOM using Jscript
  2. Do something with that entity using Jscript.

It is these 2 last steps that I wish to document in this post.

1. Get Ready

First things, first. You need a reference to the latest Jscript library and a good way to do this is to reference the one on the cloud provided by Google.


Let us ensure that the entire document object model (DOM) has been loaded by JQuery. You will typically want to put this at the end of your document.


Simple functionality

If what you want to do is a few steps, you can just include it in one big inline function within the Ready();

$(document).Ready(function(){ …… do your stuff here …… });

2. Identify (find the target of your action) – SELECTORS

There are a few ways for you to select what you are looking for,

  1. You can select by an HTML tag name (e.g. p or a or body, etc.)
  2. You can select a specific one by doing the child parent grandparent … approach
  3. You can select by CSS selectors such as classes and id
  4. You can select by HTML attribute values such as Id and Name

You can select a single or collection of entities using standard Jscript functions. Here are some of the common selection techniques.

  1. Selecting by HTML tag name

$(‘ul li a’) – select all the anchor (a) tags within the li tags within the ul tags.

$(‘ul, li, a’) – select all the anchor tags AND the li tags AND the ul tags.

  1. Selecting by element Id’s
    This is the fastest way to find a DOM element.
    $(‘#idvalue’) will select the

    Note the use of # to specify id.
  2. Selecting by element’s CSS Class name
    $(‘.FancyClass’) will select the

    Note the use of the period (.) Also note that this will end up scanning the entire DOM. You can also search for multiple classes separated with a comma, $(‘.FancyClass1, .FancyClass2’) and you can search for classes within certain tags such as $(‘Div.FancyClass’) will search for the FancyClass within all Div tags.
  3. Selecting by element’s HTML attribute value
    For instance to say, find me the Input element whose name attribute has the value: InputForm. You will do something like this: $(‘div[name=”InputForm”]’) Note: this stuff is case-sensitive!
  4. Selecting Input elements
    $(‘:input’) will select all input tags in the DOM. Note the use of the colon (:)
    $(‘:input[type=”button”]’) will select all input tags that are buttons.
  5. Using the contains() selector
    Let’s say you want to select all anchor elements that contains the text bar within it. You can use the contains() selector with the anchor tag to do this. $(‘a:contains(“bar”)’)
  6. Select even or odd members of a list
    Let’s say you want to select all even rows

    of a table. Using this $(‘tr:even’) should get you all the even rows.
  7. Selecting the first-child of an element.
    Let’s say you wish to select the first child of the element. Using $(‘body:first-child’) should get you to that element. Note. You can do this also for last-child Also, if there were more elements that you were choosing the first-child for (e.g. multiple div elements), you will get a list of first-child in that case.
  8. Using starts with (^)
    As you know, $(‘div[value=”hello world”]’) will pick the divs whose value are “hello world”, case-sensitive. However, $(‘div[value^=”hello”]’) will get you all divs whose value start with “hello”, case-sensitive.
  9. Using end with ($)
    As you know, $(‘div[value=”hello world”]’) will pick the divs whose value are “hello world”, case-sensitive. However, $(‘div[value$=”world”]’) will get you all divs whose value ends with “world”, case-sensitive.
  10. Finding elements that have an attribute containing a value (*)
    As you know, $(‘div[value=”hello world”]’) will pick the divs whose value are “hello world”, case-sensitive. However, $(‘div[value*=”o w”]’) will get you all divs whose value contains “o w”, case-sensitive.

3. Do something with what you have selected

Here, we will discuss how, once you have selected an element or a list of elements, how you can

  1. Iterate,
  2. Modify attributes, properties, values, etc.
  3. Add or remove nodes,
  4. Modify CSS classes within your DOM.


  1. Iterating through a list (each function)
    Let’s say that you select a list of divs like this,
    var divs = $(‘div’);
    Now, if you needed to iterate through this list, first you would convert the divs into a Jscript object like this $(‘#mydivs’) then use the each function to iterate through all the divs within like this, $(‘#mydivs’).each(function(index, elem){ // index is the current index and elem is the current element during the iteration }); and can this do something with the elem such as alert($(elem).text());
  2. Modify properties for DOM elements
    There are 2 ways we can do this; 1. using a Jquery api/wrapper and 2. interacting with DOM objects directly.
    Let’s say that there is a div with an id of mydiv. And we want to assign it a name of “My Div”. One way to do this would be to get that div, get its name property and assign it the value of “My Div” like, $(‘#mydiv’).name = “My Div”;
    The above example was using the raw, DOM object. If we wanted to act on a Jquery object using the Jquery API, we could,
    var foo = $(‘#mydiv’);
    $(foo).attr(‘title, ‘My Div’);
    This uses the Jquery API attr on the Jquery object $(foo) to set its title property to My Div. Note. using attr will affect one or more targets of the selector query in one call!
    You can also use JSON syntax to set multiple properties using attr like this:
    $(foo).attr({ id: ‘my id’, title: ‘my title’});
  3. Adding and removing elements (nodes) from your DOM
    To add, you will use 4 key functions:
    .append() – will append (after) the element/children
    .prepend() – will prepend (before) the element/children
    To remove nodes, simply use,
    Typically you will use .append(), .prepend() and .remove()
    So, let’s say you have $(‘.SuperClass’) and want to append the html, . You can do,
    $(‘.SuperClass’).append(‘’); .prepend() will work the same way.
    If you wanted to go in the opposite direction and wrap an element with a parent, say with a div parent, you can use the .wrap() function like this,

    ’); which will produce

    Finally, remove() will remove any selector. For instance, $(‘.one, .another’).remove(); will remove all elements that have a class of one or another.

  4. Modifying CSS styles
    The .css() function will let you get or set the value of a particular CSS attribute such as
    $(‘#mydiv’).css(‘font-weight’,’normal’); will set the font-weight property to normal for the div section identified by mydiv. To add multiple properties, use the JSON style again,
    ); This will change multiple properties.
  5. Modifying CSS classes
    There are 4 Jscript functions available to manipulate CSS classes and they are,
    .addClass() – will add a class to the DOM element
    .hasClass() – will return true or false when it checks for a class existing for the DOM element
    .removeClass() – will remove the class from the DOM element
    .toggleClass() – can toggle a class on or off depending on a return condition.
    Let’s say that you wish to add the classes class1 and class2 to the img element
    $(‘img’).addClass(‘class1 class2’);
    To use the hasClass you do something like,
    if($(‘img’).hasClass(‘class1’){ // do something }
    If you wish to remove all classes for the img element, do
    If you wish to remove specific classes from the img element, do
    $(‘img’).removeClass(‘class1 class2’);
    Finally, .toggleClass() will remove a class if it exists and add if it doesn’t, for instance,
    $(‘#helloworld’).toggleClass(‘geewiz’); will add a class geewiz to the DOM element identified by helloworld (where id=’helloworld’); and remove the class geewiz from the same DOM element if it exists when that line of code is executed. Usually works well for changing class on hover.

References – Google Hosted Libraries, including that for JScript

2 Comments Add yours

  1. Pingback: | Fresh Web!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s