1. Which, if any, of the following 3 code fragments are equivalent? Explain why they are different, if
they are. Explain why they can have different parameters and be equivalent, if they are equivalent.
//code fragment 1
$("li").each(function(idx, e) {
$(e).css(“color”, “yellow”); });
//code fragment 2
$("li").each(function() {
$(this).css(“color”, “yellow”); });
//code fragment 3
$("li").each(function(idx) {
$(this).css(“color”, “yellow”); });
[Answer]: The following 3 code fragments are equivalent because they produce the same output (changes "li" element to yellow). All these 3
fragments are looping through "li" elements, the only differents are:
1. Fragment one takes 2 arguments (index and element). During the looping process, it changes the color of every "li" based on its element from argument.
2. Fragment two does not have any argument. During the looping process, keyword "this" refers to current loop "li" element. It changes the color of each "li" element.
3. Fragment three takes 1 argument (index). During the looping process, keyword "this" refers to current loop "li" element. It changes the color of each "li" element without using any index from its argument.
2. Write a jQuery expression to find all divs on a page that include an unordered list in them, and make
their text color be blue.
<div>no ul here </div>
<div>
This does contain a ul.
<ul>
<li>the first item</li>
<li>the second item</li>
</ul>
</div>
< !—INSERT YOUR JQUERY CODE HERE - - >
<script>
$("div ul").css('color', 'blue');
</script>
</body>
3. Write jQuery code to append the following div element (and all of its contents) dynamically to the body
element.
<div><h1>JQuery Core</h1></div>
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$("body").append("<div><h1>JQuery Core</h1></div>");
</script>
</head>
<body>
</body>
</html>