There's more jQuery you could use here, but I kept it pretty much the same as yours, adding only enough to do what you wanted.
Please note that this will count ALL div
elements within #allDivs
. If there are some that you don't wish to count, another approach must be taken.
$(document.ready(function() {
$('#myButton').click(function() { // On page load, assign click event handler to your button
var nrDivs = $('div', '#allDivs').length + 1; // Retrieve all 'div' elements within '#allDivs', and get its length plus 1
var neuDiv = document.createElement("div");
neuDiv.setAttribute("Id","theDiv" + nrDivs);
neuDiv.innerHTML = "Text";
$('#allDivs').append(neuDiv);
newfeed.draw(neuDiv);
});
});
EDIT:
A more jQuery-like way:
$(document.ready(function() {
$('#myButton').click(function() { // On page load, assign click event handler to your button
var nrDivs = $('div', '#allDivs').length + 1; // Retrieve all 'div' elements within '#allDivs', and get its length plus 1
var $neuDiv = $('<div>').attr('id','theDiv' + nrDivs)
.text("Text")
.appendTo('#allDivs');
newfeed.draw(neuDiv);
});
});
EDIT:
Selectors in jQuery are very powerful and offer lots of flexibility.
For example, the line above that gets all the div
elements under #allDivs
could be re-written as:
$('#allDivs div').length + 1;
... which is exactly the same.
If you only want to get the div
elements that are immediate children of #allDivs
, use:
$('#allDivs > div').length + 1;
or
$('#allDivs').children('div').length + 1;
Another alternative would be to give these div
elements a special class that you can use as a selector. So, for example, when you create a new div
to add to #allDivs
, do it this way:
var $neuDiv = $('<div>').attr('id','theDiv' + nrDivs)
.addClass('topDiv')
.text("Text")
.appendTo('#allDivs');
Now the top div
elements in #allDivs
will have a class called `topDiv', and you can reference that in your selector like this:
$('#allDivs .topDiv').length + 1;
...which will only return div
elements that have the class topDiv
.
This only scratches the surface of what you can do with selectors in jQuery.
Hope this helps.