How to add an element after the first child div in jquery?
Assuming I have the following divs:
<div id="mydiv"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div> How can I in jquery or javascript make it so that I can add an element immediately after the first child of mydiv. Or is there some kind of selector that allows me to select and add after the first child?
<div> <div>1</div> <div>Place to Insert Subsequent div</div> <div>2</div> <div>3</div> <div>4</div> </div> +7
Rollingo
source share3 answers
To maintain readability, you can save the div you want to add to the variable:
var subsequentDiv = $('<div>Place to Insert Subsequent div</div>'); Then, using your variable, use your preferred jQuery method, in my example I use "insertAfter":
subsequentDiv.insertAfter('#mydiv div:eq(0)'); // selects children by its index, the first div is equal to 0 subsequentDiv.insertAfter('#mydiv div:lt(1)'); // selects children that its index is lower than 1 (it means the second div) Another way to achieve the same result is to read the contents of the div using the "contains filter":
subsequentDiv.insertAfter('#mydiv div:contains("1")'); 0
Ricardo castaรฑeda
source share