jQuery Basic Operations

Getting an element by Id:

$('#elmId');

Getting an element by id with characters used in CSS notation:

You need to escape CSS notational characters using “”.

<div id="my.div"></div> (id has a dot in it)
$("#my.id"); -> will not work
$("#my.div");-> works

A simple function to convert an element Id to jquery compatible format:

Below function gets an Id and replaces “:” and “.” characters with “:” and “.” respectively, with the help of a simple regular expression and “replace” function.

function jq(myId) {       
   return '#' + myId.replace(/(:|.)/g, '$1');
}

You can use this function like below:

$(jq('my.id')); $(jq('my.next.id'));

Getting an element by class:

$('.elmClass');

Getting the value of a DOM element:

$('#elmID').val();

Setting the value of a DOM element:

$('#elmID').val("value to be set");

Finding DOM elements in a document:

1- You can get the parent DOM element to look in using javascript, wrap it in a jQuery object and do a find on that object like so:

var myElm = document.getElementById('myDiv'); ->Get the div

$(myElm).find('a');->wrap the div in a jquery object and do a “find” for anchor elements in the div. This will return you the complete set of anchors in “myDiv”.

2-You can directly get myDiv using jquery and do a “find” on it in a single line like so:

$('#myDiv').find('a');

Disable/ Enable form elements:

1- Set 'disabled' attribute to 'true' or 'false'

$('#myId').attr('disabled',true);

$('#myId').attr('disabled',false);

2- Add/ Remove 'disabled' attribute

$('#myId').attr('disabled','disabled');

$('#myId').removeAttr('disabled');

to be continued…

Good Luck,
Serdar.

Leave a Reply

Your email address will not be published. Required fields are marked *