Dirk Harriman Banner Image

 

Notes jQuery


 

Basic Usage


With jQuery you select (query) HTML elements and perform "actions" on them.

$(selector).action()

$(this).hide(); // HIDES THE CURRENT ELEMENT. $("p").hide(); // HIDES ALL PARAGRAPH ELEMENTS. $(".test").hide(); // HIDES ALL ELEMENTS WITH class="test". $("#test").hide(); // HIDES THE ELEMENT WITH id="test".


The Document Ready Event

$(document).ready(function(){ // jQuery METHODS GO HERE... $("p").click(function(){ $(this).hide(); }); }); // THE FOLLOWING IS A SHORTHAND $(function(){ // jQuery METHODS GO HERE... $("p").click(function(){ $(this).hide(); }); });


Element Selection

$("p") // SELECTS ALL <p> ELEMENTS $(".className") // SELECTS ALL ELEMENTS WITH A CLASS OF className $("p.className") // SELECTS ALL <p> ELEMENTS WITH A CLASS OF className $("#idName") // SELECTS THE ELEMENT WITH AN ID idName

Element Selector List
Selector Example Selects
* $("*") All elements
#id $("#lastName") The element with id="lastname"
.class $(".intro") All elements with class="intro"
.class,.class $(".intro,.demo") All elements with the class "intro" or "demo"
element $("p") All <p> elements
el1,el2,el3 $("h1,div,p") All <h1>, <div> and <p> elements
Pseudo Element Selector List
Selector Example Selects
:first $("p:first") The first <p> element
:last $("p:last") The last <p> element
:even $("tr:even") All even <tr> elements
:odd $("tr:odd") All odd <tr> elements
Specific Pseudo Element Selector List
Selector Example Selects
:first-child $("p:first-child") All <p> elements that are the first child of their parent
:first-of-type $("p:first-of-type") All <p> elements that are the first <p> element of their parent
:last-child $("p:last-child") All <p> elements that are the last child of their parent
:last-of-type $("p:last-of-type") All <p> elements that are the last <p> element of their parent
:nth-child(n) $("p:nth-child(2)") All <p> elements that are the 2nd child of their parent
:nth-last-child(n) $("p:nth-last-child(2)") All <p> elements that are the 2nd child of their parent, counting from the last child
:nth-of-type(n) $("p:nth-of-type(2)") All <p> elements that are the 2nd <p> element of their parent
:nth-last-of-type(n) $("p:nth-last-of-type(2)") All <p> elements that are the 2nd <p> element of their parent, counting from the last child
:only-child $("p:only-child") All <p> elements that are the only child of their parent
:only-of-type $("p:only-of-type") All <p> elements that are the only child, of its type, of their parent
Relative Selectors
Selector Example Selects
parent > child $("div > p") All <p> elements that are a direct child of a <div> element
parent descendant $("div p") All <p> elements that are descendants of a <div> element
element + next $("div + p") The <p> element that are next to each <div> elements
element ~ siblings $("div ~ p") All <p> elements that are siblings of a <div> element
List Selectors
Selector Example Selects
:eq(index)$("ul li:eq(3)")The fourth element in a list (index starts at 0)
:gt(no)$("ul li:gt(3)")List elements with an index greater than 3
:lt(no)$("ul li:lt(3)")List elements with an index less than 3
:not(selector)$("input:not(:empty)")All input elements that are not empty
Semantic Selectors
Selector Example Selects
:header$(":header")All header elements <h1>, <h2> ...
:animated$(":animated")All animated elements
:focus$(":focus")The element that currently has focus
:contains(text)$(":contains('Hello')")All elements which contains the text "Hello"
:has(selector)$("div:has(p)")All <div> elements that have a <p> element
:empty$(":empty")All elements that are empty
:parent$(":parent")All elements that are a parent of another element
:hidden$("p:hidden")All hidden <p> elements
:visible$("table:visible")All visible tables
:root$(":root")The document's root element
:lang(language)$("p:lang(de)")All <p> elements with a lang attribute value starting with "de"
Attribute Selectors
Selector Example Selects
[attribute]$("[href]")All elements with a href attribute
[attribute=value]$("[href='default.htm']")All elements with a href attribute value equal to "default.htm"
[attribute!=value]$("[href!='default.htm']")All elements with a href attribute value not equal to "default.htm"
[attribute$=value]$("[href$='.jpg']")All elements with a href attribute value ending with ".jpg"
[attribute|=value]$("[title|='Tomorrow']")All elements with a title attribute value equal to 'Tomorrow', or starting with 'Tomorrow' followed by a hyphen
[attribute^=value]$("[title^='Tom']")All elements with a title attribute value starting with "Tom"
[attribute~=value]$("[title~='hello']")All elements with a title attribute value containing the specific word "hello"
[attribute*=value]$("[title*='hello']")All elements with a title attribute value containing the word "hello"
Type Selectors
Selector Example Selects
:input$(":input")All input elements
:text$(":text")All input elements with type="text"
:password$(":password")All input elements with type="password"
:radio$(":radio")All input elements with type="radio"
:checkbox$(":checkbox")All input elements with type="checkbox"
:submit$(":submit")All input elements with type="submit"
:reset$(":reset")All input elements with type="reset"
:button$(":button")All input elements with type="button"
:image$(":image")All input elements with type="image"
:file$(":file")All input elements with type="file"
:enabled$(":enabled")All enabled input elements
:disabled$(":disabled")All disabled input elements
:selected$(":selected")All selected input elements
:checked$(":checked")All checked input elements

Attributes


.addClass() Syntax

/* ADDS THE CLASSES myclass1 myclass2 TO ALL p ELEMENTS */ $("p").addClass("myclass1 myclass2"); /* REMOVES THE CLASSES myClass AND noClass, THEN ADDS THE CLASS yourClass TO ALL p ELEMENTS */ $("p").removeClass( "myClass noClass" ).addClass( "yourClass" ); /* ADD THE CLASSES selected highlight TO THE LAST p ELEMENT */ $( "p" ).last().addClass( "selected highlight" ); /* DOES THE SAME AS THE ABOVE, BUT USES AN ARRAY */ $( "p" ).last().addClass( [ "selected", "highlight" ] ); /* GIVEN AN UNORDERED LIST WITH TWO <li> ELEMENTS, THIS EXAMPLE ADDS THE CLASS "item-0" TO THE FIRST <li> AND "item-1" TO THE SECOND. */ $( "ul li" ).addClass(function( index ) { return "item-" + index; });

// CSS div.redBack {background-color:#f55;color:#ff5;} div.redBack.greenBack {background-color:#5f5;color:#579;} // HTML <div class="jq_demo1"> <div>This div should be white</div> <div class="jq_demo1 redBack"> This div will be green because it now has the "green" and "red" classes. It would be red if the addClass function failed. </div> <div class="jq_demo1"> This div should be white </div> <p class="p_demo1"> There are zero green divs </p> </div> <input type="button" id="btnDemo1" class="btn btn-bs-primary" value="Run Demo" /> // jQuery $("#btnDemo1").click(function(){ $( "div.jq_demo1" ).addClass(function( index, currentClass ) { var addedClass; if ( currentClass === "jq_demo1 redBack" ) { addedClass = "greenBack"; $( "p.p_demo1" ).text( "There is one green div" ); } return addedClass; }); });

This div should be white
This div will be green because it now has the "green" and "red" classes. It would be red if the addClass function failed.
This div should be white

There are zero green divs


.attr() Syntax

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

<div class="jq_demo2"> <input id="check2" type="checkbox" checked="checked"> <label for="check2">Check me</label> <p id="p_demo2"></p> </div> $( "input#check2" ) .on( "change", function() { var $input = $( this ); $( "p#p_demo2" ).html( ".attr( 'checked' ): <b>" + $input.attr( "checked" ) + "</b><br>" + ".prop( 'checked' ): <b>" + $input.prop( "checked" ) + "</b><br>" + ".is( ':checked' ): <b>" + $input.is( ":checked" ) + "</b>" ); } ) .trigger( "change" );

<div id="jq_demo3"> <p>Once there was a <em title="huge, gigantic">large</em> dinosaur...</p> The title of the emphasis is:<div id="jq_demo3_01"></div> </div> let title = $( "em" ).attr( "title" ); $( "div#jq_demo3_01" ).text( title );

Once there was a large dinosaur...

The title of the emphasis is:

 

The .attr() method is a convenient way to set the value of attributes—especially when setting multiple attributes or using values returned by a function. Consider the following image:

<img id="greatphoto" src="brush-seller.jpg" alt="brush seller"> // CHANGING THE alt ATTRIBUTE $( "#greatphoto" ).attr( "alt", "Beijing Brush Seller" ); // ADDING AN ATTRIBUTE $( "#greatphoto" ).attr( "title", "Photo by Kelly Clark" ); // SETTING MULTIPLE ATTRIBUTES $( "#greatphoto" ).attr({ alt: "Beijing Brush Seller", title: "photo by Kelly Clark" }); // USING A FUNCTION $( "#greatphoto" ).attr( "title", function( i, val ) { return val + " - photo by Kelly Clark"; });

<div id="jq_demo4"> <img class="img_demo4" /> <img class="img_demo4" /> <img class="img_demo4" /> </div> <div id="div_demo4"><b>Attribute of Image</b></div> $( "img.img_demo4" ).attr({ src: "images/DHH_Logo.png", title: "DHH", alt: "DHH Logo" }); $( "div#div_demo4" ).text( $( "img.img_demo4" ).attr( "alt" ) );

Attribute of Image

// BEFORE CODE RUNS <div id="jq_demo5"> <div>Zero-th <span></span></div> <div>First <span></span></div> <div>Second <span></span></div> </div> // JQUERY $( "div#jq_demo5 div" ) .attr( "id", function( arr ) { return "div-id" + arr; }) .each(function() { $( "span", this ).html( "(id = '<b>" + this.id + "</b>')" ); }); // AFTER CODE RUNS <div id="jq_demo5"> <div id="div-id0">Zero-th <span>(id = '<b>div-id0</b>')</span></div> <div id="div-id1">First <span>(id = '<b>div-id1</b>')</span></div> <div id="div-id2">Second <span>(id = '<b>div-id2</b>')</span></div> </div>

Zero-th
First
Second

<div id="jq_demo6"> <img id="img_demo6" title="DHH_Logo.png"> </div> $( "img#img_demo6" ).attr( "src", function() { return "images/" + this.title; });



 

.hasClass() Syntax

<div id="mydiv" class="class_01 class_02"></div> // RETURNS TRUE if ($( "#mydiv" ).hasClass( "class_01" )) { console.log("Has the class class_01"); } else { console.log("Does not have the class class_01"); } // RETURNS TRUE if ($( "#mydiv" ).hasClass( "class_02" )) { console.log("Has the class class_02"); } else { console.log("Does not have the class class_02"); } // RETURNS FALSE if ($( "#mydiv" ).hasClass( "class_03" )) { console.log("Has the class class_03"); } else { console.log("Does not have the class class_03"); }


// CSS div#jq_demo7 p {color:#000;font-size:1.2rem;font-weight:700;} div#jq_demo7 p.selected {color:#58a;} // HTML <div id="jq_demo7"> <p>This paragraph is black and is the first paragraph.</p> <p class="selected">This paragraph is blue and is the second paragraph.</p> <div id="result1">First paragraph has selected class: </div> <div id="result2">Second paragraph has selected class: </div> <div id="result3">At least one paragraph has selected class: </div> </div> // JQUERY $( "#result1" ).append( $( "p" ).first().hasClass( "selected" ).toString() ); $( "#result2" ).append( $( "p" ).last().hasClass( "selected" ).toString() ); $( "#result3" ).append( $( "p" ).hasClass( "selected" ).toString() ) ;

This paragraph is black and is the first paragraph.

This paragraph is blue and is the second paragraph.

First paragraph has selected class:
Second paragraph has selected class:
At least one paragraph has selected class:

.html() Syntax

In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned.

// HTML <div class="demo-container"> <div class="demo-box">Demonstration Box</div> </div> // JQUERY $( "div.demo-container" ).html(); // RESULTS <div class="demo-box">Demonstration Box</div>


// HTML <div id="jq_demo8"> <p><b>Click</b> to change the <span id="tag">html</span></p> <p>to a <span id="text">text</span> node.</p> <p>This <button name="nada">button</button> does nothing.</p> </div> // JQUERY $( "#jq_demo8 p" ).on( "click", function() { var htmlString = $( this ).html(); $( this ).text( htmlString ); });

Click to change the html

to a text node.

This does nothing.


// HTML BEFORE <div class="demo-container"> <div class="demo-box">Demonstration Box</div> </div> // JQUERY $( "div.demo-container" ) .html( "<p>All new content. <em>You bet!</em></p>" ); // HTML AFTER <div class="demo-container"> <p>All new content. <em>You bet!</em></p> </div>

$( "div.demo-container" ).html(function() { var emphasis = "<em>" + $( "p" ).length + " paragraphs!</em>"; return "<p>All new content for " + emphasis + "</p>"; });


.prop() Syntax

Disable all checkboxes on the page.

// HTML BEFORE <input type="checkbox" checked="checked"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox" checked="checked"> // JQUERY $( "input[type='checkbox']" ).prop({ disabled: true }); // HTML AFTER <input type="checkbox" checked="checked" disabled> <input type="checkbox" disabled> <input type="checkbox" disabled> <input type="checkbox" checked="checked" disabled>


.removeAttr() Syntax

<button>Change title</button> <input type="text" title="hello there"> <div id="log"></div> // SET inputTitle TO THE VALUE OF THE ATTRIBUTE title WHICH IS "hello there" let inputTitle = $( "input" ).attr( "title" ); // CREATE BUTTON CLICK FUNCTION FOR THE BUTTON $( "button" ).on( "click", function() { // GETS THE NEXT SIBLING WHICH IS THE INPUT BOX input let input = $( this ).next(); // TEST TO SEE IF THE title OF THE INPUT BOX IS EQUAL TO // THE VALUE OF THE ATTRIBUTE title WHICH IS "hello there" if ( input.attr( "title" ) === inputTitle ) { // REMOVE THE ATTRIBUTE title FROM THE INPUT BOX input.removeAttr( "title" ) } else { // SET THE ATTRIBUTE title FROM THE INPUT BOX WITH "hello there" input.attr( "title", inputTitle ); } // SHOW RESULTS $( "#log" ).html( "input title is now " + input.attr( "title" ) ); });


.removeClass() Syntax

$( "p" ).removeClass( "class_01 class_02" ); // OFTEN USED WITH addClass() $( "p" ).removeClass( "class_01 class_02" ).addClass( "class_03" );


// CSS div#jq_demo9 p {margin:0rem;border:0px none #000;padding:0.2rem 0.5rem;font-weight:700;} div#jq_demo9 p.blue {color:#58a;} div#jq_demo9 p.under {text-decoration:underline;} div#jq_demo9 p.highlight {background-color:#ff6;} // HTML BEFORE <div id="jq_demo9"> <p class="blue under">Text 1</p> <p class="blue under">Text 2</p> <p class="blue under highlight">Text 3</p> <p class="blue under">Text 4</p> <p class="blue under">Text 5</p> </div> <input type="button" id="btnDemo2" class="btn btn-bs-primary" value="Run Demo" /> // JQUERY $("#btnDemo2").click(function(){ $( "#jq_demo9 p" ).even().removeClass( "blue under" ); }); // HTML AFTER <div id="jq_demo9"> <p class="">Text 1</p> <p class="blue under">Text 2</p> <p class="highlight">Text 3</p> <p class="blue under">Text 4</p> <p class="">Text 5</p> </div> // JQUERY COULD HAVE BEEN DONE LIKE THIS: $("#btnDemo2").click(function(){ $( "#jq_demo9 p" ).even().removeClass( ["blue", "under"] ); });

Text 1

Text 2

Text 3

Text 4

Text 5


.removeProp() Syntax

// HTML <div id="jq_demo10"> <p>Item 1</p> </div> <input type="button" id="btnDemo3" class="btn btn-bs-primary" value="Add Property" /> <input type="button" id="btnDemo4" class="btn btn-bs-primary" value="Show Property" /> <input type="button" id="btnDemo5" class="btn btn-bs-primary" value="Remove Property" /> // JQUERY $("#btnDemo3").click(function(){ $("#jq_demo10 p").prop("itemId", 1234); }); $("#btnDemo4").click(function(){ para = $( "#jq_demo10 p" ); $("#jq_demo10 p").append( "The secret itemId is: ", String( para.prop( "itemId" ) ), ". " ) }); $("#btnDemo5").click(function(){ $("#jq_demo10 p").removeProp("itemId"); });

Item 1

     

.toggleClass() Syntax

Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.

// INITIAL HTML <div class="tumble">Some text.</div> // APPLY JQUERY CODE FIRST TIME $( "div.tumble" ).toggleClass( "bounce" ) // AFTER FIRST TOGGLE <div class="tumble bounce">Some text.</div> // APPLY JQUERY CODE SECOND TIME $( "div.tumble" ).toggleClass( "bounce" ) // AFTER SECOND TOGGLE <div class="tumble">Some text.</div>


.val() Syntax

Get the current value of the first element in the set of matched elements or set the value of every matched element.
The .val() method is primarily used to get the values of form elements such as input, select and textarea.

At present, using .val() on <textarea> elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR, however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:

$.valHooks.textarea = { get: function( elem ) { return elem.value.replace( /\r?\n/g, "\r\n" ); } };

// GET THE VALUE FROM THE SELECTED OPTION IN A DROPDOWN LIST $( "select#foo option:checked" ).val(); // GET THE VALUE FROM A DROPDOWN SELECT DIRECTLY $( "select#foo" ).val(); // GET THE VALUE FROM A CHECKED CHECKBOX $( "input[type=checkbox][name=bar]:checked" ).val(); // GET THE VALUE FROM A SET OF RADIO BUTTONS $( "input[type=radio][name=baz]:checked" ).val();

Dropdown Lists

Get the single value from a single select and an array of values from a multiple select and display their values.

// CSS div#jq_demo11 { display:flex; flex-flow:row wrap; justify-content:flex-start; align-items:flex-start; align-content:flex-start; margin:0rem; border:0px none #000; padding:0rem; text-align:top; vertical-align:top; height:10rem; } div#result_11 { margin:0.12rem 1rem; border:0px none #000; padding:0.5rem 0.75rem; } .form_select_jq { margin:0.12rem; border:1px solid #000; border-radius:0.25rem; padding:0.5rem 0.75rem; } // HTML <div id="jq_demo11"> <select id="ddlSize" class="form_select_jq"> <option value="">Select A Size</option> <option value="16">Pint</option> <option value="12">Bucket</option> <option value="8">Rocks</option> <option value="2">Shot</option> </select> <select id="ddlDrink" class="form_select_jq" size="3" multiple> <option value="Whiskey">Whiskey</option> <option value="Gin">Gin</option> <option value="Beer">Beer</option> <option value="Coca Cola">Coca Cola</option> </select> <input type="button" id="btnDemo6" class="btn btn-bs-primary" value="Show Selected" /> <div id="result_11"></div> </div> // JQUERY FOR VALUES $("#btnDemo6").click(function(){ let ddlSize = $( "#ddlSize option:selected" ).val(); let ddlDrink = $( "#ddlDrink" ).val() || []; let ddlDrinkText = $( "#ddlDrink option:selected" ).text() || []; let outHtm = ddlDrink.join(", ") +" in "+ ddlSize; $("#result_11").html(outHtm); }); // JQUERY FOR TEXT $("#btnDemo7").click(function(){ let outHtm = ""; let ddlSize = $( "#ddlSize option:selected" ).text(); let ddlDrinkText = $( "#ddlDrink option:selected" ).toArray().map(item => item.text).join(); outHtm += ddlDrinkText +" in "+ ddlSize; $("#result_11").html(outHtm); });

       
Getting The Text Instead Of Value With Multiple Selection List

It should be noted that the above code breaks if instead of getting the value from the multiple selection list the text is referenced. The error is in the join. If the code was:

let ddlDrink = $( "#ddlDrink option:selected" ).text() || []; ddlDrink.join(", ");

Does not retuen a delimited list, but it concatenates the selected values as a single string such as "Apple JuiceOrange Juice". To get each of the selected items requires different code than the simple code used to get the values.

let ddlDrinkText = $( "#ddlDrink option:selected" ).toArray().map(item => item.text).join();