w3resource

jQuery Effect: jQuery Code to get a single element from a selection

jQuery Effect : Exercise-7 with Solution

Write a jQuery Code to get a single element from a selection.
Sample Data :

HTML code:

<body>
<ui>
<li>Html Tutorial</li>
<li>Mongodb Tutorial</li>
<li>Python Tutorial</li>
</body>

Solution:

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Write a jQuery Code to get a single element from a selection</title>
</head>
<body>
<p> Click this paragraph to see it fade.</p>
</body>
</html>

JavaScript Code :


$( "p:first" ).click(function() {
  $( this ).fadeTo( 500, 0.40 );
});

Note : In jQuery .on( events [, selector ] [, data ], handler ) method is used to attach an event handler function for one or more events to the selected elements.. It has the following parameters :

  • events : Space-separated event (one or more) types and optional namespaces, such as "click" or "keydown.myPlugin". [Type: String]
  • selector : Filter the descendants of the selected elements that trigger the event. [Type: String]
  • data : Data to be passed to the handler in event.data when an event is triggered. [Type: Anything]
  • handler : A function to execute when the event is triggered. [Type: Function( Event eventObject [, Anything extraParameter ] [, ... ] )]

Live Demo:

See the Pen jquery-effect-exercise-7 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Animates a paragraph to fade to an specified opacity (complete the animation within 500 milliseconds).
Next: Toggle between fading in and fading out different boxes

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.