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, settingthis
to that element and setting the attribute to the result of the function. – Heretic Monkey Commented Mar 4, 2019 at 22:11
1 Answer
Reset to default 4jQuery'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条)