How to access elements with specific class as soon as document has loaded

时间:2017-04-09 23:54:06

标签: jquery

I have several occurrences of the following html:

<label class="control-label translate">Color </label>

I want to grab the text of each label with the class translate as soon as the document has loaded and put together the following jQuery to test how to do that.

$(document).ready(function () {

$(".translate").each(function(index,item) {
    alert("text: " + $(item).text());
})
});

Doesn't look like the function is being executed because I don;t see any alert messages. There are no errors in the js console.

What did I miss?

2 个答案:

答案 0 :(得分:1)

Your code works fine, but I think you forgot to include jQuery. Just add this to the beginning of the HTML page. I suspect this is the case if you're getting no feed back. You can also see if $ is defined in console.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$(document).ready(function () {
  $(".translate").each(function(index,item) {
      alert("text: " + $(item).text());
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="control-label translate">Color </label>

答案 1 :(得分:0)

Sorry guys, stupid mistake on my part which I just noticed. All working fine now. Pete