简体   繁体   中英

How to iterate through jQuery elements

I want to be able to see what's inside the tags that jQuery finds. How come the following doesn't work?

 $("div.UIImageBlock_Content.UIImageBlock_ICON_Content").each ( function() {
     alert(($this).html);
 });

What's the right way to do this?

  • $this => $(this)
  • .html => .html()

So this should do it:

$("div.UIImageBlock_Content.UIImageBlock_ICON_Content").each ( function() {
     alert($(this).html());
 });

Note that html() function just uses the innerHTML property, so it can be a lot simpler:

$("div.UIImageBlock_Content.UIImageBlock_ICON_Content").each ( function() {
     alert(this.innerHTML);
 });

The current element within a jQuery each iteration can be accessed via this (not $this ).

There's a small caveat, however: the this in a jQuery iteration refers to each element's underlying DOM object, not the jQuery object. You can use this code, then:

$("div.UIImageBlock_Content.UIImageBlock_ICON_Content").each ( function() {
    alert(this.innerHTML);
});

You don't need to build a jQuery object from the raw DOM object on each iteration — an element's inner HTML is already present in the DOM object, and there's no need for extra work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM