0

I have the following TypeScript function:

$.each($("[data-static-map-image]"), function () {
    $(this).attr("src", $(this).data("mapImageUrl"));
});

I would like to convert this into an Arrow function. Unfortunately, I can't figure out how to make it work with the each loop. Can someone give me a hint?

P.S. I ask for your indulgence as I am still in the beginning of the learning phase.

2
  • 1
    Why are you using jQuery in 2022? Commented Jul 14, 2022 at 5:56
  • It is unfortunately given within the scope of the project I am involved in. So I have to use it. Commented Jul 14, 2022 at 6:00

2 Answers 2

1

The jQuery documentation on jQuery.each explains that the callback gets arguments:

callback
Type: Function( Integer indexInArray, Object value )
The function that will be executed on every value.

So if you really want to stick with jQuery, then make use of the arguments passed to the callback function:

$.each($("[data-static-map-image]"), (i, elem) => {
    $(elem).attr("src", $(elem).data("mapImageUrl"));
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can do this in plain JavaScript (and TypeScript too)

Use querySelectorAll to get all elements matching your selector and then use the Array#forEach function:

const allElements = Array.from(document.querySelectorAll('[data-static-map-image]'))

allElements.forEach(element => {
  const url = element.getAttribute('data-mapImageUrl')
  element.setAttribute('src', url)
})

The main reason you cannot use an arrow function in your context is because this refers to the outer scope as opposed when using anonymous functions which have their own this which jQuery is going to bind to each of the elements

4 Comments

There is no need to call Array.from.
True. But I find it very convenient as NodeList is missing some of the Array functional predicates such as filter
In that case, you don't need forEach, and can use the callback argument of Array.from.
That'd be mapping each of the elements into a new Array in case we still store stuff into a variable and resulting an array of undefined if we forget to return the element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.