gravitation
gravitation

Reputation: 1957

Append text to an attribute rather than replacing it?

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

Upvotes: 26

Views: 35490

Answers (3)

Seth Battis
Seth Battis

Reputation: 147

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.

Upvotes: 4

Kharisma Wijaya
Kharisma Wijaya

Reputation: 421

I know this question is 7 years old. Just in case someone came across this question, here's the solution without using .each:

$('.theclass').attr("title", function() { return $(this).attr("title") + "Appended text." });

Upvotes: 42

strager
strager

Reputation: 90022

In that context, $(this) is not the element of $('.theclass'). Maybe you want to use each:

$('.theclass').each(function() {
    $(this).attr("title", $(this).attr("title") + "Appended text.");
});

Upvotes: 29

Related Questions