recently I refactored one of my earlier project where I wrote ES5. There were parts where I had to retrieve DOM elements using document.getElementById(id) by their id
And then I refactored the code by using ES6 proxy. For example, I have a html file containing
<div class="bottom">
<div class="add">
<div class="add__container">
<select class="add__type" id="addType">
<option value="inc" selected>+</option>
<option value="exp">-</option>
</select>
<input type="text" class="add__description" id="addDescription" placeholder="Add description">
<input type="number" class="add__value" id="addValue" placeholder="Value">
<button class="add__btn" id="addButton">
<i class="ion-ios-checkmark-outline"></i>
</button>
</div>
</div>
then I used proxy to retrieve the DOMs like this
const {
addType,
addDescription,
addValue,
addButton,
budgetContainer,
budgetIncomeList,
budgetExpensesList,
budgetValue,
budgetIncomeValue,
budgetExpensesValue,
budgetExpensesPercentage,
monthLabel,
} = new Proxy({}, { get(_, id) { return document.getElementById(id); } });
It worked, but I was wondering if this is a good practice to retrieve DOM elements.
Also I just found that, after I commented out the retrieve part of the code i.e. the snippet above with Proxy. I can still access DOM elements in my Js file directly using their IDs without defining them! I didn't know anything about this before.
Sorry I know this looks like two different questions but I really wish you guys can share some knowledge about these.