Vanilla javascript: How to access DOM elements properties through a function parameter?

I am very new to Javascript (to programing in general also). I am trying to make a function that will take in a parameter (the DOM element’s name) to access its DOM properties.

For example, I have multiple DOM elements created beforehand:

const aGatherPlants = document.createElement('p');
aGatherPlants.className = 'gather-plants btn btn-medium btn-dark mrgn-b';
aGatherPlants.appendChild(document.createTextNode(`Plants [${costGatherPlants}]`));
aGatherPlants.style.display = 'none';
aGatheringTab.appendChild(aGatherPlants);

const aGatherWood = document.createElement('p');
aGatherWood.className = 'gather-wood btn btn-medium btn-dark mrgn-b';
aGatherWood.appendChild(document.createTextNode(`Wood [${costGatherWood}]`));
aGatherWood.style.display = 'none';
aGatheringTab.appendChild(aGatherWood);

My goal is to access those element’s properties, such as element.style, element.appendChild, element.addEventListeners, etc. in a function.

function functionName(property){
  property.style.display = 'none';
}

functionName('aGatherPlants');

Obviously, it doesn’t work and browser console is logging cannot access property .style of undefined.

I want to make a single function to access all DOM elements created, instead of having to hard code every single one of them.

Can anyone help out a newbie here ? If you need more information, please let me know.

122 thoughts on “Vanilla javascript: How to access DOM elements properties through a function parameter?”

  1. i need a loan with no credit, i need a loan help please. i need a loan long term need loan now need a loan been refused everywhere can i get loan modification, cash advance loans online, cash advance loans, cash advances, do cash advance loans affect your credit. Investment assets and liabilities investment, internationally active.

    Reply

Leave a Comment