javascript - Vanilla js equivalent of jquery .attr( attributeName, function ) - Stack Overflow

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

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();
  });
});

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();
  });
});
Share Improve this question asked Mar 4, 2019 at 22:08 drmrbrewerdrmrbrewer 13.2k24 gold badges98 silver badges212 bronze badges 1
  • 3 I find it educational to look at the source code of libraries I use so I know what they're doing. Here's the source for attr. If you look at the documentation you point to, you can see that sending a function calls that function for each element in the jQuery object, setting this to that element and setting the attribute to the result of the function. – Heretic Monkey Commented Mar 4, 2019 at 22:11
Add a ment  | 

1 Answer 1

Reset to default 4

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))
})

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745102479a4611358.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信