-->

I want to change the style of all sibling elements

2020-07-27 05:43发布

问题:

I am using buttons for a tabbed navigation interface. I want to have the active tab red, and the rest black.

<div class="tabs">
<button type="button" onclick="selectTab(this);">Astringents</button>
<button type="button" onclick="selectTab(this);">Exfoliators</button>
<button type="button" onclick="selectTab(this);">Moisturizers</button>
</div>

function selectTab(activeTab){
var siblings = activeTab.parentNode.childNodes;
for (s in siblings){
s.style.color='black';
}
activeTab.style.color='red';

I am having problems accessing the siblings properly. There are more buttons than these three so I need to solve this dynamically. I will be using Ajax so this page will not reload.

回答1:

You are trying to do extra work... Why not keep a reference to the currently selected tab, then when a new selection is made, reset its style.

Also, it is much better to use CSS classes than inline styles for this (this way, you don't need to muck about with Javascript to change how your tabs look):

<style>
  .tab { color: black; }
  .tab-selected { color: red; }
</style>
<div class="tab" onclick="selectTab(this)">Tab 1</div>
<div class="tab" onclick="selectTab(this)">Tab 2</div>
<!-- More tabs -->

<script>
   var selectedTab = null;
   function selectTab(tab) {
     if (selectedTab) { selectedTab.className = 'tab'; }
     tab.className = 'tab-selected';
     selectedTab = tab;
   }
</script>