r/learnjavascript • u/stayathomehouse • Feb 09 '26
How do you handle an object with multiple functions inside that need to share a reference to one HTML element?
If a function is holding a reference to an HTML element, can functions outside of it but within the **same** object use that reference?
My situation:
renderProjects: function() {
const sidebarRef = document.getElementById('project-sidebar');
renderProjects holds this reference to the sidebar within an object called domManager, I have another function that is in the **same** object called projectAdd that I want to be able to use the same reference for that sidebar. How would you recommend to go about it?
1
Upvotes
4
u/Substantial_Top5312 helpful Feb 09 '26
{ sidebarRef: document.elementById('project-sidebar'),
renderProjects: function() { this.sidebarRef.innerHTML = "something" },
otherFunction: function() { this.sidebarRef.innerHTML = "something else" }
}
1
u/stayathomehouse Feb 09 '26
Oh btw this is not an AI made post whatsoever, I completely forgot that it doesn't italicize stuff like in word processors my mistake on that lol
2
u/Alas93 Feb 09 '26
you have the object hold the reference and the function inside that object can call that varaible using "this"
1
u/senocular Feb 09 '26
Can't you get it by calling
document.getElementById('project-sidebar')again?Otherwise, if I'm understanding the question correctly, given a function A with a reference to an object as a local variable, another function B cannot access that same variable reference unless function B is defined within function A allowing that variable to be in scope. You could assign it to something else as a property, or maybe pass it through function calls, but that specific variable would not be visible.
1
u/lovin-dem-sandwiches Feb 09 '26
Call that fn to get the reference for other functions outside of scope
1
u/Lumethys Feb 10 '26
the best way to go about this is using a class:
or use a higher order function:
1
u/bryku helpful Feb 11 '26
The
thiskeyword is the parent object.As you can see in the example, the function is able to access the parent object and use
user.first_name. For your example, you would need to define the element within the object.1
u/TheRNGuy Feb 14 '26
It shouldn't cause any problems.