Created
September 3, 2013 19:17
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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