What is the idea behind setting the attributes twice, once in html and then in jquery?

panarama

New Member
#1
I am new to javascript and jquery and i was looking at some code and found this to be very prevalent everywhere.
Mã:
<ul class="items">     
<li class="item" aria-controls="item-0" role="tab"> </li>
<li class="item" aria-controls="item-1" role="tab"> </li>
<li class="item" aria-controls="item-2" role="tab"> </li>
</ul>
The attributes to "item" class are set in html but then they are set again in jquery. Why?
Mã:
$(".items").find(".item").each(function () {
                    $Item = $(this);
                    $Item.attr("aria-controls", "item-" + (count));
                    $Item.attr("role", "tab");
                    count++;
                    });
 

Admin

Administrator
Thành viên BQT
#2
What you are looking at is not actually a duplication of the code or data, what you are seeing in the HTML is the final rendering after the javascript you provided has run.
Essentially the javascript you provided is finding any child of items with the class of item and is iterating through each element. After that it is updating some attributes to change the role and aria-controls. This is an easy way to set the same attributes on multiple items or to (as shown here) append to a single item through each iteration.
Mã:
var count = 0;
$(".test").find("p").each(function () {
  $Item = $(this);
  $Item.attr("id", "child" + count);
  $Item.attr("class", "extended-child");
  count++;
 });
Mã:
.extended-child {
    color: red;
}
Mã:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
  <p>Hello</p>
  <p>World</p>
</div>
In the above example for example, after iterating through and p child elements the class will be updated to make the text red and the ID will be set. You will notice initially there is no class however after there is a class applied. If you were to inspect this in your browser however you would see:
Mã:
<div class="test">
   <p class="extended-child" id="child0">Hello</p>
   <p class="extended-child" id="child1">World</p>
</div>
However as you have seen that is not the initial HTML that was added.

EDIT
Below is a carbon copy of the above except I will update the HTML again. After 3 seconds the class will update changing the text color.
Mã:
var count = 0;
$(".test").find("p").each(function () {
  $Item = $(this);
  $Item.attr("id", "child" + count);
  $Item.attr("class", "extended-child");
  count++;
 });
 
 setTimeout(function(){
 $(".test").find("p").each(function () {
  $Item = $(this);
  $Item.attr("class", "extended-child-two");
 })
 }, 3000)
Mã:
.extended-child {
    color: red;
}

.extended-child-two {
    color: green;
}
Mã:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
  <p>Hello</p>
  <p>World</p>
</div>
 
Top