I have a requirement for giving unique id's for <div> in XSL. Please help.

Recommended Answers

All 6 Replies

The variable example works, but there is a much easier way to do it (in my opinion). Let's say, in your XML, you have the element "events" repeating 31 times -- indicating 31 events -- and you want each one to have a unique ID.

In your XSL sheet, you'd run a loop creating a <div> like this:

<div id="event-{position()}"><xsl:value-of select="event" /></div>

And that would create a div with a unique ID for every event listed.

The curly braces are required around the XSL function position() because XSL functions need to be "enclosed" when used by HTML tags.

Hope that helped,
floatingDivs

The reason I pointed to the variable option, is that the question is not clear. If there is only one loop, then yes, I agree with you. If there are more however, the position will not give the desired results.

hielo,

That could work, but the problem becomes if you want to do anything with CSS. For instance, if you wanted to alternate background colors for even and odd-numbered <div>'s, you couldn't with the generateid() function, since it creates a random ID. By using a variable, you can check the position() and create an attribute that determines whether a <div> is even or odd numbered. Still, good contribution and it might be exactly what they're looking for!

That could work, but the problem becomes if you want to do anything with CSS. For instance, if you wanted to alternate background colors for even and odd-numbered <div>'s,

Not a problem. Add a common class the elements in question - say "group1":

$("div.group1:even").css("background-color","khaki")
$("div.group1:odd").css("background-color","lightblue")
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.