Using recursion to build unique names

Hey forums,

I built out some code you might want to play with. I wanted to have the flexibility to build out unique IDs for nested elements so I can put multiple versions of a symbol on the stage and not worry so much about naming conventions, except for the top level and then I can make all the code target the unique nested elements.

For each nested element give it a unique class name. In the case of my test I used level1 for the top level, then level2 for the nested element and level3 for the element nested in level2.

So in Hype I have a function called rename:

function rename(hypeDocument, element, event){
var nameList = new Array();
var test = findTopLevelParent(element, “level1”, nameList, hypeDocument);
if(test.length > 0){
element.id = test.join(".")+"."+element.classList[1];
}else{
element.id = element.classList[1];
}

   console.log(element.id);

}

then in an external js I have this code:

function getWrappedParent(target, hypDoc){
return target.parentElement.parentElement;
}

function findTopLevelParent(target, targetName, nameList, hypDoc){
var compare = getWrappedParent(target, hypDoc);
var parentName = compare.classList[1];
if(parentName == null){
return nameList;
}
if(parentName == targetName){
nameList.unshift(compare.classList[1]);
return nameList;
}else{
nameList.unshift(parentName);
return findTopLevelParent(compare, targetName, nameList, hypDoc);
}
}

when I run this the output in the console is as such:

level1
level1.level2
level1.level2.level3

I’m pretty stoked about this because it allows a very simple way to name elements but keep it sensible so you can build out complex structures generically, and target any nested element easily.

1 Like

Cleaned the code up some more.

Here is the new rename:

function rename(hypeDocument, element, event){
        var nameList = new Array();
	var test = findTopLevelParent(element,nameList, hypeDocument);
	if(test.length > 0){
		element.id = test.join(".")+"."+element.classList[1];
	}else{
		element.id = element.classList[1];
	}
}

and the new findTopLevelParent:

function findTopLevelParent(target, nameList, hypDoc){
	var compare = getWrappedParent(target, hypDoc);
	var parentName = compare.classList[1];
	if(parentName == null){
		return nameList;
	}
	nameList.unshift(parentName);
	return findTopLevelParent(compare, nameList, hypDoc);

}
2 Likes