Reputation: 15778
With jQuery latest one:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.js"></script>
Could someone explain what are the differences between:
$(document).ready(function () {
$('.produit').append('<img src="img.png" alt="altimg" />');
});
and:
$(document).ready(function () {
$('.produit').append($('img').attr({ 'src':'img.png', 'alt':'altimg' }));
});
=> the first code works, but the second adds the image many times (seven times exactly) then throws a JavaScript Exception:
Cannot read property 'cycleW' of undefined
"next is undefined
"...
I'm a JavaScript beginner and I thought those two codes would do the same...
... any idea?
Upvotes: 1
Views: 106
Reputation: 75993
'<img src="img.png" alt="altimg" />'
is the string version of $('img').attr({ 'src':'img.png', 'alt':'altimg' })
.
There isn't a loop in the second code block but if there are more than one .produit
elements then they will all get an image element appended to them.
To inspect the second code block a little closer:
$('img')
: this creates an img
element.attr({ 'src':'img.png', 'alt':'altimg' })
: this gives the new img
element a src
and an alt
attribute.It's useful to create your DOM elements like this if you are allowing user input to become part of the element. It helps against injection attacks where a user could alter the HTML of your page if you just concocted a string of their input.
Alnitak had a very good observation that $('img')
selects all the img
elements in the DOM and $('<img />')
actually creates an img
element.
Upvotes: 0
Reputation: 6131
$('img') selects all the images in your html then .attr sets the attributes. If you want you can select the img element like this :
$('img[src=img.png][alt=altimg]')
but it WON'T create a new element. it will select one in your document.
As for your .append call, it appends the html you pass in argument to your element.
Upvotes: 0
Reputation: 339786
Your second code has an error.
It should be:
$('<img>', ...);
To create a new element the tag needs angle brackets around it!
As written, it's selecting every existing image tag on the page, and appending them to every instance of .produit
.
Ideally you should also use the map version of $('<tag>')
, rather than calling .attr
afterwards:
$('<img>', {src: 'img.png', alt:'altimg'}).appendTo('.produit');
Upvotes: 3