2.13 JS Vs JQuery
2.13 JS Vs JQuery
});
▣ This is to prevent any jQuery code from running before the
document is finished loading (is ready).
EXAMPLE
▣ Here are some examples of actions that can fail if methods are
run before the document is fully loaded:
▣ Trying to hide an element that is not created yet
▣ Trying to get the size of an image that is not loaded yet
jQuery Selectors
▣ jQuery selectors allow you to select and manipulate HTML
element(s).
▣ jQuery selectors are used to "find" (or select) HTML elements
based on their name, id, classes, types, attributes, values of
attributes and much more.
▣ All selectors in jQuery start with the dollar sign and parentheses:
$().
The element Selector
▣ The jQuery element selector selects elements based on the
element name.
▣ You can select all <p> elements on a page like this:
▣ $("p")
<!DOCTYPE html>
<html> <head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3
.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(“tr:odd").hide();
});
});
</script> </head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
Example: Select
Elements by Name
<script>
$(document).ready(function () {
});
</script>
<body>
<div>
<p>hello</p>
<p></p>
</div>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
Select Elements by Id
▣ The following figure shows which DOM elements will be returned from $
('#myDiv1') & $'(#prg2').
The .class Selector
▣ The jQuery .class selector finds elements with a specific class.
▣ To find elements with a specific class, write a period character,
followed by the name of the class:
▣ $(".test")
<head><script>
$(document).ready(function(){
$("button").click(function(){
$(“p.test").hide();
});
});
</script> </head>
<body>
<h2 class="test">This is a heading</h2>
<p class="test">This is a paragraph.</p>
<p class=“test2”>This is another paragraph.</p>
<p
<p
<button>Click me</button>
</body>
More Examples of jQuery Selectors
<script>
$(document).ready(function(){
// Highlight only paragraph elements with class mark
$("p.mark").css("background", "yellow");