timkl
timkl

Reputation: 3339

Determine number of divs with jQuery

I'm using jQuery Tools (http://flowplayer.org/tools/index.html) to create tooltips, I've created a js-file that holds the following lines:

$("div#example-0").tooltip('#example-0-tooltip');
$("div#example-1").tooltip('#example-1-tooltip');
$("div#example-2").tooltip('#example-2-tooltip');
$("div#example-3").tooltip('#example-3-tooltip');

etc.

This works fine if there's a known number of example-divs, however I would like this to work with an unknown number of example-divs.

Basically I would like my jQuery to be able to read the DOM-tree and determine how many example-divs there is and somehow loop through them all and add the tooltip.

Anyone know how to do this?

Upvotes: 2

Views: 302

Answers (5)

tvanfosson
tvanfosson

Reputation: 532435

Use the starts with attribute matcher and iterate. Grab the id from the current element and invoke the tooltip.

$('div[id^=example-]').each( function() {
    $(this).tooltip( '#' + $(this).attr('id') + '-tooltip' );
});

Or, if they each had the same class in addition to unique ids.

$('div.exampleClass').each( function() {
    $(this).tooltip( '#' + $(this).attr('id') + '-tooltip' );
});

Or if, as @Savageman suggests, you can get away with reusing the same named DIV for the tooltip (and use a class to mark all divs that need a tooltip).

$('div.exampleClass').tooltip('#exampleTooltip');

Upvotes: 8

andyface
andyface

Reputation: 946

not sure if this helps, but there's a tooltip plugin for jquery which can use the title attribute of a tag to generate a tooltip. It does it automatically, so you wouldn't have to set a statement for each, just have a title assigned to the div.

Upvotes: 0

Eugeniu Torica
Eugeniu Torica

Reputation: 7574

Put a certain class to all divs. Essential code will remain the same.

Ex:

<div id="1" class="tooltip">
</div>

<div id="2" class="tooltip">
</div>
<div id="3" class="tooltip">
</div>
<div id="4" class="tooltip">
</div>

and the code:

$("div.tooltip").tooltip('#example-0-tooltip');

Upvotes: 0

krb
krb

Reputation: 16315

This returns element number :

$('element').size();

Upvotes: 0

BalusC
BalusC

Reputation: 1108632

Give them all the same class so that you can just do

$('div.classname').tooltip(...);

Upvotes: 1

Related Questions