首页 > 解决方案 > 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();
  });
});

标签: javascriptjquery

解决方案


.attr带有函数的 jQuery对查询结果中的每个元素进行操作。相当于

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 版本

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

推荐阅读