Counters
When adding a new element to the page you may be tempted to update some innerHTML with a count of elements
Example code
const newElement = this.addNewElement() // Adds a new section to .sections
const sections = newElement.parentElement.querySelector('.sections')
const numberOfSections = sections.querySelectorAll(".section").length
const sectionTitle = newElement.querySelector('p.section-title')
sectionTitle.querySelector('.counter').innerHTML = numberOfSections
<div class="sections">
<div class="section">
<p class="section-title">
Section number <span class=".counter"></span>
</p>
</div>
<div class="section">
<p class="section-title">
Section number <span class=".counter"></span>
</p>
</div>
</div>
Use CSS Counters
.sections {
counter-reset: section;
}
.section {
counter-increment: section;
}
.counter:before {
content: counter(section);
}
Form Inputs
When you have a form input outside a form you may be tempted to add hidden fields and update their values when the external input changes.
Example code
<form id="my-form">
<input type="hidden" name="view-options">
<button type="submit">Save</button>
</form>
<select data-input-name="view-options">
<option value="list">List</option>
<option value="grid">Grid</option>
</select>
const select = document.querySelector('[data-input-name]')
const inputName = select.dataset.inputName
const input = document.querySelector(`[name="${inputName}]`)
select.addEventListener("change", (event) => {
input.value = event.target.value
})
Use form
attribute
<form id="my-form">
<button type="submit">Save</button>
</form>
<select form="my-form">
<option value="list">List</option>
<option value="grid">Grid</option>
</select>