Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Saturday, August 24, 2013

FIND() selector in Jquery


To make partial views to preserve the values while doing the http post we need to pass the top level model(parent view model) to partial view.
find() lets you filter on a set of elements based on a selection you've already made. For example if you wanted to set the back-ground color to all the spans inside a div, you could write:

$('#testDiv').find('span').css('background-color', 'red');

We can do the same by using below syntax
$('#testDiv span').css('background-color', 'red');


Here “testDiv” is a div tag.


Find selector is a much faster comparative to above one.

Identifying the elements by attribute values in Jquery

$(‘element[attribute=”value”]’): Selects all elements that have the specified attribute with a value exactly equal to a specified value.
Ex:  $('span[id="spnTest1"]').css('background-color', 'red');

$(‘element[attribute^=”value”]’): Selects all elements that have the specified attribute with a value beginning with specified value. The comparison is case sensitive.
Ex: $('span[id^="span"]').css('background-color', 'blue');

$(‘element[attribute$=”value”]’): Selects all elements that have the specified attribute with a value ending with specified value. The comparison is case sensitive.
Ex: $('span[id$="test3"]').css('background-color', 'yellow');

$(‘element[attribute*=”value”]’): Selects all elements that have the specified attribute contains sub string of specified value. The comparison is case sensitive.
EX: $('span[id*="test"]').css('background-color', 'green');

Basic selectors in Jquery

Identifying the element by tag  name
Ex: $('p') -> selects all paragraphs in the document

Identifying the element by ID
Ex: $(‘#divUser’) -> selects a DOM element which contains ID as “divUser”.

Identifying  the element by class

Ex: $(‘.divUser’) -> selects a DOM element which contains class as “divUser”.

Adding a custom Jquery function to check whether a element exists in a html page or not using Jquery

Please add the below code your custom .JS file

(function($) {
    if (!$.exist) {
        $.extend({
            exist: function(elm) {
                if (typeof elm == null) return false;
                if (typeof elm != "object") elm = $(elm);
                return elm.length ? true : false;
            }
        });
        $.fn.extend({
            exist: function() {
                return $.exist($(this));
            }
        });
    }
})(jQuery);

Usage
------------
// With ID
$.exist("#eleID");
// OR
$("#eleID").exist();

// With class name
$.exist(".class-name");
// OR
$(".class-name").exist();

// With just a tag // Probably not best idea as there will be other tags on the site
$.exist("div");
// OR
$("div").exist();