user1367922
user1367922

Reputation: 229

Add new Attributes to a HTML string with JQuery

i have a problem to add a new attribute to an existing html string.

First i read the HTML-code from a editor and save it as String.

Then i can acces attributes from this string with:

$("img", $(htmlString)).attr("src");

But if i try to add a new attribute (eg. name), it doesn't work. To do this i try:

$("img", $(htmlString)).attr("name", "fooo");

So my problem is, that i need to add a new attribute with some value and at the end i should have a new HTML-string wich contains the old HTML code with the new added attributes. I hope someone can help me.

Upvotes: 2

Views: 5103

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

I want to copy the value from src, modify it, and save in a new attribute in the same img tag. Only the save part doesn't work

Try this:

var $img = $("img", $(htmlString));
var src = $img.attr("src");
src = src.replace(".jpg", ".png");
$img.attr("data-src", src);

This will turn this:

<img src="/images/myimage.jpg" alt="Example image" />

In to this:

<img src="/images/myimage.jpg" data-src="/images/myimage.png" alt="Example image" />

This is assuming there is only 1 img tag in htmlString. If you have more than one, you will need to loop through each one.

Upvotes: 3

Related Questions