I have a html structure in my webpage as below :
<div class="group_name">Group A</div>
<div class="student_name">Studen 1</div>
<div class="student_name">Studen 2</div>
<div class="student_name">Studen 3</div>
<div class="group_name">Group B</div>
<div class="student_name">Studen 1</div>
<div class="student_name">Studen 2</div>
<div class="student_name">Studen 3</div>
..
.
.
Now this structure is dynamically generated using PHP. What I want to do is, I want to add below code as a last element of “Group A” :
<div class="student_name">Studen 4</div>
But I want to add it using jQuery, as I am getting this “Student 4” record as a Ajax response string. So the div is getting added based on the Group Name. At the moment I have used static value for group name as “Group A”. So the Javascript will be something like below :
$(".group_name").each(function(index){
var group_name = $(this).text();
if(group_name=='Group A'){
// Add Student 4 to last position of this group
}
});
So this way I am already selecting the “Group A” element. But now I want to add “Student 4” as the last entry in that group (below “Student 3”).
How can I do this ?
Thanks in advance.
What this code does:
$('.group_name')select all groups.filter(...)reduces it to the element with the correct group name. I did not use:contains()as that would perform a substring match instead of an exact match..nextUntil('.group_name')takes all following siblings which are not a new group.filter('.student_name')removes all elements that are not student elements – just in case your DOM structure is bad enough to make this necessary.last()reduces it to the last one – the place after which the new one should be inserted.after(...)inserts the new entry after that element.Here is a demo: http://jsfiddle.net/ThiefMaster/5UHgC/
Please note that you could make this much easier, cleaner and more structured by changing your structure like this:
Then you could simply use this: