how do i find a bunch of elements after page load and regroup them inside a new div?
So yes, my head hurts. What i aim to achieve:
i have content that is generated dynamically from php inside a page, eg, i use a PHP include to fetch content. Now once this content has loaded, i wish to use javascript/jQuery in order to find certain elements by ID, see if theres more than one, if there is, then group them in a new div开发者_开发技巧.
For example; i have a div named 'pony', the page has 3 other divs, also named 'pony', using javascript/jQuery i wish to house them in a new div named 'horse' which will be generated on the fly. I should also say the new div has to be generated at the top of the page.
But i have a div named 'cows' and there is only one, i want js/jQuery to ignore that one.
Does anyone know how to do this? Rather if PHP would be easier, then id welcome the knowledge of that too.
Having mutliple elements with same ID is not valid.
However if you cannot avoid it, then try using something like this:
$(function(){
var ponies = $("[id='pony']");
if(ponies.length > 1){
$("<div id='horse' ></div>").prependTo("body").append(ponies);
}
});
If you use a class to define the previous divs, you can use the $(".pony") selector to have a count of the number of divs generated dynamically, then create a new DOM element called 'horse' and append the previous pony divs to it as such:
$(function() {
var listPony = $(".pony");
if (listPony.length >= 3)
{
var newDiv = $("<div class='horse'></div>").append(listPony);
$('body').prepend(newDiv);
}
});
Full example here:
http://jsfiddle.net/CPAfA/
精彩评论