Skip to content

Instantly share code, notes, and snippets.

@EtienneLem
Created September 3, 2013 19:17
Show Gist options
  • Save EtienneLem/6428322 to your computer and use it in GitHub Desktop.
Save EtienneLem/6428322 to your computer and use it in GitHub Desktop.
$('div').add_at_index(content, index) adds an element at a given index.
// Works with Zepto/jQuery
$.fn.add_at_index = function(content, index) {
if (index < 0) { index = 0 }
this.each(function() {
var $this = $(this)
var $child = $this.children().eq(index)
if ($child.length) { return $child.before(content) }
$this.append(content)
})
}
$div = $('div')
$div.html('<i>1</i><i>3</i>')
$div.add_at_index('<i>2</i>', 1)
console.log($div.html()) // => <i>1</i><i>2</i><i>3</i>
$div.add_at_index('<i>999</i>', 999)
console.log($div.html()) // => <i>1</i><i>2</i><i>3</i><i>999</i>
$div.add_at_index('<i>-10</i>', -10)
console.log($div.html()) // => <i>-10</i><i>1</i><i>2</i><i>3</i><i>999</i>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment