How can I access these elements using jQuery to add and remove a class on click? -


I have several undocumented lists, which are being dynamically created for the loop. The problem is that I can not just target elements in this ul, it is changing the active class for every one. I am finding it difficult to understand what a brother is, a cousin etc. I have tried some of the closest (), siblings (), past (), find () and some of them different combinations, but this may not seem to work out.

Here is the HTML

  & lt; Ul & gt; & Lt; Li & gt; & Lt; A href = "#" square = "active button" & gt; Option 1 & lt; / A & gt; & Lt; / Li & gt; & Lt; Li & gt; & Lt; A href = "#" square = "button" & gt; Option 2 & lt; / A & gt; & Lt; / Li & gt; & Lt; Li & gt; & Lt; A href = "#" square = "button" & gt; Option 3 & lt; / A & gt; & Lt; / Li & gt; & Lt; Li & gt; & Lt; A href = "#" square = "button" & gt; Option 4 & lt; / A & lt; / Li & gt; & Lt; / Ul & gt;   

JS

  var set_active = $ ('.button'); Set_active.on ('click', function () {var $ this = $ (this); var other = set_active.not ($ this); $ this.addClass ('active'); others.removeClass ('active') ; // This will remove all other active // ​​states, what do I need to do, // it only selects siblings?));    

You can only reduce it by:

 < Code $ ('.button'). Click (function () {$ (this) .parents ('ul'). ('A.button') RemoveClass ('active'); $ (this) .addClass ('active');});             , it first reaches the parent  ul , then searches for all  a.button  elements for kids And removes the active class of them all then it applies to the active class on the element that was just clicked.   

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -