Reputation: 20004
.prepend()
works when there is one line of code such as .prepend("<li>item1<li>")
but when I try to put a big block of code in it, such as multiple divs with classes etc, it doesn't work. I did however, see that you can pass it a function but I can't figure out the syntax.
If I need to use $(selector).prepend(function(index,html))
instead please help me use this.
Edit: I got it working by passing a function into it, I still don't understand how to use the index,html parameters.
Upvotes: 1
Views: 2876
Reputation: 14205
You should create string...
var myString = '<div class="lorem"><div id="temp" class="ipsum"></div></div>';
and then prepend it:
$(selector).prepend(myString);
Note: Always reduce DOM insertions to a minium. Working solution: http://jsfiddle.net/mCUWe/
EDIT: If you want to format your markup you're able to do something called string concatenation. Works as well: http://jsfiddle.net/mCUWe/1/
var myString = '<div class="lorem">LOREM'
+'<div id="temp" class="ipsum">IPSUM'
+'</div></div>';
Update 02/2017
Nowadays I recommended to go with ES2015 Template-Strings
Upvotes: 2
Reputation: 30111
The index
parameter will tell you the position of the current element in the selector
The html
parameter will tell you the old html for the current element
For example, if you want have a ul
and want to to insert the li
number to the begging:
$('ul').find('li').prepend(function(index, html){
return 'li number ' + index;
})
Upvotes: 1