drmrbrewer
drmrbrewer

Reputation: 12989

Vanilla js equivalent of jquery .attr( attributeName, function )

I note that jQuery .attr() has a variant which allows you to set an attribute name to a function: see here.

I'm trying to find the plain vanilla js equivalent of this, but note that the setAttribute() function only appears to allow you to set an attribute value to a string: see here.

More specifically, I'm trying to convert a snippet from this article from jQuery to plain js:

$(function(){
  $('.stroke-double, .stroke-single').attr('title', function(){
    return $(this).html();
  });
});

Upvotes: 1

Views: 7646

Answers (1)

Phil
Phil

Reputation: 164760

jQuery's .attr with a function operates on each element in the query result. The equivalent would be something like

function attrEquiv(selector, attr, setterFunction) {
  document.querySelectorAll(selector).forEach((el, i) => {
    el.setAttribute(attr, setterFunction.call(el, i, attr)) // bind `el` to `this`
  })
}

attrEquiv('.stroke-double, .stroke-single', 'title', function(index, attr) {
  return this.innerHTML
})

ES5 version

var elements = document.querySelectorAll(selector)
Array.prototype.forEach.call(elements, function(el, i) {
  el.setAttribute(attr, setterFunction.call(el, i, attr))
})

Upvotes: 4

Related Questions