1. Adding jQuery to Your Web Pages
Selecting DOM Element:
jQuery selects elements the same way CSS does. You already know more about jQuery than you realize.
CSS selectors select elements to add style to those elements; jQuery selectors select elements to add behavior to those elements. We can select an element based on its name, class, ID, attribute, attribute value and much more.
$(“Canbe”) Note Canbe can be element, class, Id.
Selecting by Element name:
The first we have to use jQuery method to select some document elements to act upon. We will use most powerful and frequently use jQuery’s $() function: the selection of DOM elements via selectors. For example, we will select all h1 heading in page as $(“h1”)
- Add some JQuery action : $(“h1”).text(“Hi All”);
An example above will delete and add new text to all h1 as Hi All, the $ is an alias or shortcut of jQuery() function which returns jQuery object containing a set of DOM elements that match the given criteria and also expose many of jQuery’s methods and properties. One of jQuery’s main strengths is that it allows you to work with the DOM
The jQuery syntax for selecting HTML elements and performing some action on the element(s).
Basic syntax is: $(selector).action()
- $ sign to define/access jQuery
- (selector) to “query (or find)” HTML elements
- jQuery action() to be performed on the element(s)
Examples: $(“p”).hide() – hides all <p> elements.
Note: We need to add DOM ready function, to make sure that DOM has finished loading before we can reliably use jQuery.
Selecting with ID and class
$(“#container”); Select the html elmenent with ID container.
$(‘.country’); Select the html element with .country class.
JQuery Selector example
- Select all li element inside of ul with class breakfast and modifies new text “Eat Well”