jQuery is a powerful tool that lets you add functionality to what would otherwise be hard-coded HTML scripts by injecting javascript into it.
This works by "wrapping" HTML code in dynamic Javascript that can be manipulated.
The power of $:
- I hope you appreciate the pun I just made.
- The hidden abilities of jQuery are unlocked with the $ and paired with (). Once you create the $('') you can start to inject the HTML code within it. For instance: $('< h1>Hello World!') {< space added before h1 so format would display correctly when live}will create a header in the HTML document that says "Hello World!"
Adding content to tags with jQuery:
- While we can declare tags easily with jQuery, there are steps we can use to add content to tags later on. Example:
//declare an empty set of tags
let $empty = $('
//add content
$empty.text('This headline is no longer empty!');
- We can also manipulate and add content to entire types of HTML code by using .html(). This method tells the interpreter to apply changes to all tags of the same type
$('ul').html('Placeholder Text');
This example takes all instances of unordered lists and applies the "Placeholder Text" content to all instances instead of just one.
Methods for combining tags:
- Since jQuery is similar to Javascript, it comes with methods we can use to manipulate the code we are writing. For instance, we can create a body tag, and then later on, add code to the body by using appendTo or prepend. Example:
let $body = $('
');let $paragraph = $('
This is an example of how we can write a line of jQuery code and add it to another tag
')$paragraph.appendTo($body);
This makes the browser interpret the HTML as
This is an example of how we can write a line of jQuery code and add it to another tag
- Also like Javascript, we can chain together different methods. So if we wanted to add a class to the paragraph while we appended it to the body, we could do this: $paragraph.appendTo($body).addClass('examples');
Conclusion:
jQuery is a powerful tool that takes HTML up a notch and makes, what would normally be hardcoded, dynamic and adjustable and lively. It's worth learning to make your websites less static.
Top comments (0)