...

View Full Version : Organizing elements into a container element according to class



poisonborz
09-20-2011, 11:49 PM
Hola,

I have a problem where I have a number of random set of elements that have a fixed rule for class name. I want to move them to a container element according to this class name.

So for example the site generates

<p class="dog-1"></p>
<p class="dog-2"></p>
<p class="cat-1"></p>
<p class="dog-3"></p>

My output would be ideally

<div class="dog">
<p class="dog-1"></p>
<p class="dog-2"></p>
<p class="dog-3"></p>
</div>

<div class="cat">
<p class="cat-1"></p>
</div>

When searching for a solution, all I could find was simple ordering of elements according to class...
Thanks

Old Pedant
09-21-2011, 12:47 AM
Are you going to give us a list of the possible class names (e.g., "dog-#" and "cat-#") or does the code also have to search out those? If so, how can we tell the difference between "dog-1" and "heading-donotchange-1"? That is, can you be sure that there never be a class name ending in "-1" or "-2" that should *not* have this grouping applied to it?

poisonborz
09-21-2011, 01:45 AM
Yes, I can control the class naming, so they will always follow the scheme <containername>-<number> (as in dog-1)

Old Pedant
09-21-2011, 04:02 AM
<html>
<head>
<style type="text/css">
div.dog {
font-family: arial;
font-size: small;
color: red;
}
div.dog p {
background-color: pink;
}
div.cat {
font-family: times;
font-size: xx-large;
color: blue;
}
div.cat p {
background-color: lightblue;
}
</style>

<script type="text/javascript">
var prefixes = ["dog","cat"];

function reOrg(prefix)
{
var outer = document.createElement("div");
outer.className = prefix;
var paras = document.getElementsByTagName("p");
for ( var p = 0; p < paras.length; ++p )
{
var para = paras[p];
if ( para.className.substring(0,prefix.length) == prefix )
{
var inner = document.createElement("p");
inner.innerHTML = para.innerHTML;
outer.appendChild(inner);
para.style.display = "none";
}
}
document.body.appendChild(outer);
}
function reOrgAll( )
{
for ( var r = 0; r < prefixes.length; ++r )
{
reOrg( prefixes[r] );
}
}
window.onload = reOrgAll;
</script>
</head>
<body>
<p class="dog-1">WOOF!</p>
<p class="cat-1">meow</p>
<p class="dog-2">bark bark</p>
<p class="dog-3">arf arf arf</p>
</body>
</html>

Try commenting out the line in magenta, above, to see that it really is working.

poisonborz
09-21-2011, 10:36 AM
Just what I needed, thanks a lot!! :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum