How to reference the currently selected item in jQuery?

I am trying to create a script that will insert an element imgafter each link to a specific site with the source code equal to the attribute value of hrefthis link. Here is what I came up with:

$("a[href*=site.com/img/]").after("<img src="+$(this).attr("href")+">");

The problem is that it $(this)does not work (attr () returns undefined). Why is this? How to refer to the selected link and its argument href?

+3
source share
1 answer

Expand it manually with each (), for example:

$("a[href*=site.com/img/]").each (function () {
    $(this).after("<img src="+$(this).attr("href")+">");
});

You need to be in the right area for $ (this) in order to behave as you expect, jQuery needs some kind of context to set it up.

+8
source

Source: https://habr.com/ru/post/1751688/


All Articles