开发者

Iterate and process child elements with jquery - proper use of $(this)

I'm trying to get j开发者_如何学Pythonquery to find pairs of elements, take the value of one, process it and make it the value of the next one, rinse and repeat.

        $(function() {

                $("div").each(function() {
                var longURL = $(this).attr("href");
                $(this).html("processed "+longURL);
                });

        });

    <div class="long" href="plop"></div>
    <div class="short" href="plip"></div>
    <div class="long" href="plopouze"></div>

output is :

processed plop
processed plip
processed plopouze

So this works, since it selects all the divs, somehow proving that each() can handle multiple objects ; But I fail to understand how to properly select back those $(this) objects using a class selector, something like $(this).(.myclass) (in this case $(this).('.short')) does not work..?


I'm not sure what you are trying to do, but if you only want to select divs with a certain class, you can do that.

$("div.long").each(function() {
  var longURL = $(this).attr("href");
  $(this).html("processed "+longURL);
});

This will only loop over divs with the class long.

Or, you can use .hasClass to see if an element has a certain class.

$("div").each(function() {
  if($(this).hasClass('long')){
    var longURL = $(this).attr("href");
    $(this).html("processed "+longURL);
  }
});

This will loop over all divs, and then check the class of each one to see if it's long.


If you want to check if $(this) has class .short you can use $(this).is('.short').


There are a number of functions you can look into to select elements with different relationships to $(this)

  • To see if your element has a descendant, use .has()
  • To see if your is something (a class, or element type for example) use .is()
  • For any type of tree traversal, like looking for ancestors, descendants, children or siblings, have a look at this list of tree traversal methods.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜