JQuery Selectors & Methods

To be good at JQuery, it is very important to understand and know how to select the HTML DOM elements. In this blog, I just wanted to provide some examples (more on the lines of a cheat sheet) of JQuery selectors which I use most often. I also wanted to document some of the methods that I use most of the times. I didn't want to go through JQuery documentation all the time. As I said, this list is not comprehensive but these are the items I use the most.

Selectors
  • $ is same as jquery.
  • $('#id') selects the element with id = id
  • $('p') selects all <p> elements
  • $('p,a,span') selects all paragraphs, anchor and span tags
  • $('ancestor descendants') selects all the descendants of ancestor. For ex. $('table tr') selects all tr tags in the table element. Descendants are children, grandchildren etc of ancestor.
  •  $('.classname') selects all elements which have class = classname
  • $('.classA,.classB') selects all elements which have either classA or classB
  • $('p.classA') selects only <p> tags which have class = classA
  • $('a[title]') selects all <a> tags which have a title attribute
  • $('a[title="somelink"]') selects all <a> tags which have title attribute =   somelink
  • $(':input') selects all input elements including input, textarea, select, button, image, radio, checkboxes etc. $('input') will select only <input> elements. Textarea is also input element but its written like <TextArea> that's why :input is handy.
  • $('div:contains("internet")') selects all the div elements whose value contains the text "internet"
  • $('tr:odd') and $('tr:even') selects all the odd and even rows respectively.
  • $('tr:first-child') and $('tr:last-child') selects the first and the last row respectively
  • $(input[value^="internet"]) selects all inputs whose value attribute STARTS with the word "internet"
  • $(input[value$="internet"]) selects all inputs whose value attribute ENDS with the word "internet"
  • $(input[value*="internet"]) selects all inputs whose value attribute CONTAINS the word "internet"
  • $('input', $('#mainDivs')) will find all inputs inside the mainDivs element
  • $('div:eq(0)', $('#mainDivs')) will find the first div inside the mainDivs element
Methods
.ready()- Specify a function to execute when the DOM is fully loaded.
.on()- Attach an event handler function for one or more events to the selected elements.

function notify() { alert("clicked"); }
$("button").on("click"notify);

function greet(event) { alert("Hello "+event.data.name); }
$("button").on("click", { name: "Karl" }, greet);


  • .each(function(index, Element)) - loops through each element. It also provides the index of the item being looped. The current item can be referenced by using $(this) or using $(Element) where Element is the input passed. Usually we dont need to use $(Element) as $(this) does the job. So mostly the usage of each is like .each(function(index)).
  • .html() - gets the html. 
  • .html(htmlString) - sets the html of the referenced element by htmlString.
  • .attr("id") - gets the value of the attribute id.
  • .attr("id","5") - sets the value of attribute id to 5.
  • .attr({"title":"some title", "alt":"5"}) - sets multiple attributes using JSON object. Text inside {} is a JSON object.
  • $('.phone').append("<br/>Ph: 123-456-7890") will APPEND the phone number to all elements which have class phone.
  • $('.phone').prepend("Ph: 123-456-7890<br/>") will PREPEND the phone number to all elements which have class phone.
  • $('.phone').wrap("<div></div>") will WRAP the div around all elements which have class phone.
  • $('.phone').unwrap() will UNWRAP the parent around all elements which have class phone.
  • $('.classA').css("border", "2px red solid") will apply border style with value 2px red and solid on all elements which have class = classA
  • $('.classA').css({"border":"2px red solid","font-size":"16px"}) will apply multiple styles (border and font-size) to elements with classA using JSON object
  • val() - gets the value of the element
  • val(str) - sets the value of the element to str
  • $('#t1').addClass("classexample") - adds the class classexample to element id #t1
  • $('#t1').removeClass("classexample") - removes the class classexample from element id #t1
  • $('#t1').toggleClass("highlight") - toggles the class i.e if class is applied, it removes it, if its not there, it adds it
  • $('#id').clone() - clones the id element
Events
  •  $('#id').click(function(){ // do something }) will register a click event to element with id = id
  • $('#id').change(function(){ // do something }) change is mostly used for <select> elements. It gets fired  everytime selection is changed. Inside the function $(this) will give you the changed value. change also works with textarea and input also.
  • $('#id').mouseenter(function(){ // do something}) is for mouseenter
  • $('#id').mouseleave(function(){ // do something}) is for mouseleave
  • $('#id').bind("mousenter", mouseEnterFunc) - binds the mouseenter event to item with id = id.
  • $('#id').bind("mouseenter mouseleave mouseup", bindingExample) - bind's main advantage is that it allows you to bind multiple events in a simple manner. Then in the bindingExample method, you can use e.type to see which event is called in case you want to do different things.
  • $('#id').bind({mouseenter:funcenter, mouseleave:funcleave, mouseup:funcup}) - will do the same thing as above but in JSON object
  • $('#id').unbind() - unbinds all the events associated with id
  • $('#id').unbind("mouseenter") - unbinds only the event specified
  • $('#id').delegate('input','keypress' function() { // do something }) - bind and delegate are similar. the only difference is that when you attach events through bind, any elements added through code or after load, the event will not get attached to these new elements. If you use delegate, it will keep on monitoring and even if new elements are added, it will attach the event handler. In this example, for anything under the context of id, a keypress event is attached to all inputs. When keypress happens, function will get called. You can use the undelegate function to get rid of event handlers.
  • $('#id').hover(func1, func2) - func1 is mouseenter and func2 is mouseleave.
  • $('#id').hover(func1) - func1 will be used as mouseenter and mouseleave. Its a good place to use toggleClass method.
  • $('#id').toggle(func1, func2, callback) - when you click id, first func1 will get called, at 2nd click func2 will get called. In the end callback will be called. This is good place to add some class in func1 add a different class in func2 and then remove the classes in callback. 4th click will then again call func1.
  • $('#id').toggle() - hides or shows the element. You can also provide a boolean for show and hide or duration and callback for it to fade out etc.
AJAX Functions
  • $('#id').load() - loads HTML data from the server. It provides capabilities to get parts of html by providing selectors or if the page takes arguments, we can send the arguments as well using JSON object. It also provides a call back function after the load is completed.
  • $.get(url,data,callback,type) - fires a get request. data is data sent to the server. callback contains the data returned from server apart from other arguments such as textStatus and jqXHR which is jquery XML Http Request object. type is the type of data server will return (HTML, XML, JSON)
  • $.getJson(ur, data, callback) - similar to get with type = JSON.
  • $.post(url,data,callback,type) - fires a post request. rest is same as get.
  • $.ajax({//settings json object}) - the low level api. Load, Get, Post all of them ultimately fire ajax function. ajax function arguments can be provided in the form of a json object and it provides more control with what we want to do with ajax calls.
CSS Selectors
  • #id word following after # is the id of the element to which css can be applied
  • .class word following after . is the class of elements to which css can be applied
Other Notes
  •  Document.Ready is called when the page is loaded. i.e HTML DOM is loaded. It may mean that all images have not been loaded yet but DOM is loaded.
  • keyword this represents the raw DOM object while $(this) represents the raw DOM object wrapped inside jquery. Therefore, $(this) has jquery methods available to it while this does not. this has access to raw properties though.
  • CDN benefits - faster, cached, 99.9% uptime. Good for internet apps. For Intranet better to have your own copy.
Write the code for selecting the
1st div element, 4th div element
last div, and for even and odd div elemets also.
one by one?
apply the red color on the above div. 

<div class="questions">
        <div class="box"Question</div>
    <div class="box"Question</div>
    <div class="box"Question</div>
    <div class="box"Question</div>
    <div class="box"Question</div>
    <div class="box"Question</div>
</div>

Code for first div    : $("div.questions > div:first").css("color""red");
Code for 4th div         :  $("div.questions > div:nth-child(4)").css("color""red");
Code for last div        :  $("div.questions > div:last").css("color""red");
Code for even div        :  $("div.questions > div:even").css("color""red");
Code for odd div         :  $("div.questions > div:odd").css("color""red");
Code for second last div :  $("div.questions > div::nth-last-child(2)").css("color", "red");
   
What are the advantages of using jQuery over JavaScript?
  1. Jquery is well written optimised javascript code so it will be faster in execution unless we write same standard optimised javascript code.
  2. Jquery is concise java script code ,means minimal ammount of code is to be written for the same functionality than the javascript.
  3. Javascript related Development is fast using Jquery because most of the functionality is already  written in the library and we just need to use that.
  4. Jquery has cross browser support ,so we save time for supporting all the browsers. 
What are features of JQuery 
or 
What can be done using JQuery?

1. One can easily provide effects and can do animations.
2. Applying / Changing CSS.
3. Cool plugins.
4. Ajax support
5. DOM selection events
6. Event Handling

If you have a table, how you will apply the two differt color on alternate rows using Jquery?
$(document).ready(function () {
    $("tr:even").css("background-color""#f4f4f8");
    $("tr:odd").css("background-color""#ffffff");
});

What is the use of jquery load() method?
The jQuery load() method is a powerful AJAX method.
The load() method loads data from a server and puts the returned data into the selected element without reload the complate page.

Ex:The following example loads the content of the file "demo_test.txt" into a specific <div> element
$("#div1").load("demo_test.txt");

window.onload vs document.ready jquery
suppose in the HTML Page you have Created a img tag. Now in Jquery u want to get the Height of Image.

$(document).ready(function() {
    alert($('#logo').height());
});​

document.ready is fired when the DOM has loaded,it does not take gaurantee of loading
all the assets in the page. so information like height isn't available.

window.onload = function(){
    alert($('#logo').height());
}

window onload waits for the assets in the page to be completely loaded,
so information such as height is now available.

Difference between onload() and document.ready() function used in jQuery?
  • We can add more than one document.ready() function in a page.
  • we can have only one onload function.
  • Document.ready() function is called as soon as DOM is loaded.
  • body.onload() function is called when everything (DOM, images)gets loaded on the page.

1 comment:

  1. đồng tâm
    game mu
    cho thuê nhà trọ
    cho thuê phòng trọ
    nhac san cuc manh
    số điện thoại tư vấn pháp luật miễn phí
    văn phòng luật
    tổng đài tư vấn pháp luật
    dịch vụ thành lập công ty trọn gói
    lý thuyết trò chơi trong kinh tế học
    đức phật và nàng audio
    hồ sơ mật dinh độc lập audio
    đừng hoang tưởng về biển lớn ebook
    chiến thắng trò chơi cuộc sống ebook
    bước nhảy lượng tử
    ngồi khóc trên cây audio
    truy tìm ký ức audio
    mặt dày tâm đen audio
    thế giới như tôi thấy ebook

    Trương Thiên Sư lại thêm một phen kinh ngạc không thôi, những gì Lưu Phong nói đối với lão tựa hồ có kích thích rất lớn, tuy chỉ là trong nháy mắt, Lưu Phong cảm giác được lão đã già nua đi rất nhiều.

    " Công tử, ta phải tự mình suy ngẫm một chút, ngươi về trước đi, qua vài ngày nữa ta sẽ tìm ngươi." Trương Thiên Sư khoát khoát tay, ý bảo Lưu Phong có thể đi.
    Lưu Phong rất mừng rỡ rời đi, nghĩ thầm sớm biết như vậy, ta đem chuyện này nói từ lúc nãy có phải giờ đây đã sớm được về nhà rồi không.

    " Lão Thiên Sư a, người tự mình bảo trọng."

    " Lão Thiên Sư a, lần sau không nên tìm ta vào buổi tối, ta nhiều việc bề bộn......"

    …………dọc theo đường đi Lưu Phong chạy đi nhanh như điện chớp đích, sợ bỏ lỡ cơ hội chiêm ngưỡng suối phun.

    Chỉ là, nhiều việc không theo ý người.

    Ngay trên đường về nhà đột nhiên xuất hiện một bóng người.
    Một nữ tử che mặt dáng vẻ yêu kiều nhưng lại mang theo khí tức uy hiếp ngăn trở đường đi của hắn.

    " Tránh ra, chó ngoan không cản đường" Vừa vất vả thoát khỏi lão đạo sĩ, bây giờ lại gặp phải tiểu nữ nhân, làm cho Lưu Phong muốn bốc hỏa.

    " Người chính là Tuần Sát sứ Cẩm Y Vệ?" Nữ tử che mặt tựa hồ cũng không để ý thái độ của Lưu Phong đối với nàng.Ngữ khí có vẻ ôn nhu, rất là thú vị. Muốn cho Lưu Phong thú vị chính là thưởng lãm cúc hoa của nàng.

    ReplyDelete

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives