coder
coder

Reputation: 716

Can not iterate over elements in Jquery

I have function:

 <script type="text/javascript">
    $(document).ready(function () {
        $('#myTab a').click(function (e) {
            e.preventDefault();
            if ($(this).attr('href') === ('#' + $('#myTabContent').children('div').attr('id'))) {
                alert($(this).attr('href'));
            }
        });
    });
</script>

and markup:

 <ul id="myTab" class="nav nav-tabs">
    <li><a href="#vergiSK" data-toggle="tab">
        </a></li>
    <li><a href="#spkSK" data-toggle="tab">
        </a></li>
    <li><a href="#hukukSK" data-toggle="tab">
       </a></li>
</ul>
<div id="myTabContent" class="tab-content">
    <div class="tab-pane fade" id="vergiSK">
     <ul>
        <li></li>
        <li></li> 
     </ul>
   </div>
    <div class="tab-pane fade" id="spkSK">
      <ul>
        <li></li>
        <li></li> 
     </ul>
    </div>
    <div class="tab-pane fade" id="hukukSK">
      <ul>
        <li></li>
        <li></li> 
     </ul>
    </div>
 </div>

The problem is that when I click on one of 'a' elements I am getting only element with first ID. How can I get all matched 'href' and values of 'id'?

Upvotes: 0

Views: 275

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

If you're trying to get the div related to the anchor you're clicking, then:

<script type="text/javascript">
    $(document).ready(function () {
        $('#myTab a').click(function (e) {
            var $div = $($(this).attr("href"));
            // Do something with the div
        });
    });
</script>

That works because the value of the href you're using (#vergiSK and such) is a valid ID selector, so you can pass it directly into $() to get a jQuery object wrapped around the element with that ID. Note that I'm using $(this).attr("href") to get the href rather than just this.href, which would be expanded (so would have the full URL, not just the actual content of the href attribute).

Live Example (turns the divs red briefly when you click the corresponding link) | Source

But if for some other reason you want to loop over the elements of #tab-content's children, you'd use each.

$('#myTabContent').children('div').each(function() {
    // Raw DOM element for each child `div` is `this`
});

Upvotes: 2

Related Questions