I’m trying to remove attribute "selected" from span element when other span element (not the same div) is clicked
and
How to remove attribute "selected" of span element in div_bottom1 while div1 another span is selected?
<script type="text/javascript">
window.addEventListener('DOMContentLoaded',() => {
const div1 = document.getElementById('div1');
div1.addEventListener('click', (e) => {
const div1span = e.target.closest('span.swatch');
if (!div1span) return;
const dj = document.getElementById('div_bottom1');
const djp = document.getElementById('div_bottom2');
const dd = document.getElementById('div_bottom3');
if (div1span.matches('.div1swatch')) {
const clodj = dj.closest('span.selected');
const clodd = dd.closest('span.selected');
clodj.removeProperty('selected');
clodd.removeProperty('selected');
}
});
</script>
It works till getting div1span.matches('.div1swatch')
and then:
"Uncaught TypeError: Cannot read properties of null" error
div 2-4 are separate divs outside div1 and have style.display = "none";
set while div1span is switched
Clicking on div1span
sets style.display = "none";
to div_bottom2
and div_bottom3
.
Clicking on div2span
sets style.display = "none";
to div_bottom1
and div_bottom3
Clicking on div3span
sets style.display = "none";
to div_bottom1
and div_bottom2
Is it related?
What I’m doing wrong? I’m javascript newbie, coding in php + html so far
2
Answers
Store in a variable
let elBoxSelected;
the selected item (Element)Assign a click to all(!) your boxes (not only to the ones in
#div1
)The entire functionality can be achieved without any JavaScript but with just pure HTML/CSS. It only requires some markup changes and applying some fitting css rules.
The usage of the
<label/>
/<input type="radio"/>
relationship together with the functional:has()
CSS pseudo-class mainly does the trick and enables keyboard navigation as well.