Append text to an attribute rather than replacing it?

后端 未结 3 1094
梦毁少年i
梦毁少年i 2021-02-07 02:01

I want to append some text to the title attribute of all elements of a certain class.

3条回答
  •  别那么骄傲
    2021-02-07 02:29

    JQuery has come a ways. There's a version of .attr() that takes a function as the value argument:

    $('.theclass').attr('title', (i, value) => `${value || ""}appended text`);
    

    i is the index of the attribute, value is the current value of the attribute... which might not be set, hence the value || "" expression, to avoid converting undefined into the string 'Undefined' uglily.

提交回复
热议问题