I’m starting to use JavaScript and jQuery a bit more than just to do some shiny effects and I have a question about a fundamental thing in jQuery. I often have no idea what I’m really working with in jQuery.
For example, if a have the following markup:
<img class="image" src="picture.png" width="100" height="100" />
And in jQuery do
var img = $('.image');
img then is not the same as when I do
var img = $('<img class="image" src="picture.png" width="100" height="100" />');
But if I for example want to create a new image on image and run some jQuery functions on it, like .css(), I have to do:
var img = $('<img class="image" src="picture.png" width="100" height="100" />');
img.appendTo('.myElement');
$('.image').css("border","none");
Which is kind of a double step?
My Question: What are the different typs of things I’m handeling with here? What’s the difference between the fist two examples? I want to understand what actually the elements are I’m daling with when working with jQuery/JavaScript.
My Question [Update]: I may have been a bit unclear, I don’t want to know what the examples actually do, but what I select/create when I call these functions (a pointer to an DOM element, a string in JavaScript that represents HTML but still has to be added to the DOM to be displayed, etc.).
When you pass a selector (e.g.
$('.image')) to the jQuery function, it does just that: selects. The jQuery object will contain all elements that are already present in the DOM that match that selector.When you pass a HTML string to the jQuery function, it creates a jQuery object that contains the element(s) that the HTML represents. However, it doesn’t automatically add them to the DOM, so you can’t select them; you need to use one of the various methods to add them –
.append(),.appendTo(),.before(),.after(), etc.Your CSS manipulation example, however, is flawed, because you can chain jQuery functions together. You can combine that into a single line of code:
If that’s all you want to do with the element, then you don’t even need to save it to a variable. If, however, you’re going to want to use it again later, then it may be faster to do so; depends on exactly what you’re going to be doing with it.