Overview: We will be going over what the DOM is to Javascript, as well as how to interact with elements and their properties/attributes inside the DOM in both Javascript and jQuery. Today will be the most basic lesson by far.
$('#theId')
$('.theClass')
$('[name="theName"]')
document.getElementById('theId')
document.getElementsByClassName('theClass')
document.getElementsByName("theName");
<button name="someButton">Click Me!</button>you should use
$('button[name="someButton"]'), note we are telling jQuery we are looking specifically for a button who's name is 'someButton' and not just anything with the name 'someButton'.
<button id="someButton">Click Me!</button>looks like just plain HTML. However Javascript sees this HTML element quite differently. Let's select this element with JS and also with jQuery and see what we get:
console.log($('#someButton'));
console.log(document.getElementById('someButton'));
console.dir()rather than
console.log()
console.log()and identify some properties you might know already.
See the Pen ZaJgpE by Mike Parda (@mikeparda) on CodePen.
See the Pen WXzyzY by Mike Parda (@mikeparda) on CodePen.
See the Pen VrXdVz by Mike Parda (@mikeparda) on CodePen.
See the Pen QOmxzo by Mike Parda (@mikeparda) on CodePen.
.addClass()is less code to write, however it is still going to execute the same JS code as if we did it manually. Always keep this in mind when using jQuery, just because you write less code, does not mean the browser executes less code. You could very easily take our JS code, put it into a function, and now it is reusable and just as easy to call as it's jQuery counterpart.
.addClass()function would not really be grounds to import the jQuery library. Even if you do have jQuery loaded into your project, it is perfectly acceptable to use plain JS, and in fact much easier on the browser, so I would encourage using regular old JS whenever it is "almost as easy" as using jQuery to save your client some processing power.
spanthat says "i am the span". Let's say I want to add the
spanelement to a
divthat is already on the page:
See the Pen pdLZPj by Mike Parda (@mikeparda) on CodePen.
See the Pen bYvjrX by Mike Parda (@mikeparda) on CodePen.
See the Pen jazpzW by Mike Parda (@mikeparda) on CodePen.
See the Pen WXJQyb by Mike Parda (@mikeparda) on CodePen.
See the Pen jaxbwO by Mike Parda (@mikeparda) on CodePen.
display: none;. Even if we used CSS3 to fade then remove the element, we have no way to know when the element has finished fading. jQuery, as well as our function, both provide a callback function that will execute when the animation is complete.