2

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.

3
  • I think you forgot to add a closing bracket. Commented May 1, 2012 at 14:41
  • What do you need the new attribute for? If you're just storing arbitrary information, the data() method is a better choice all around. Commented May 1, 2012 at 14:41
  • 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. Commented May 1, 2012 at 14:45

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I have one more question. is there only the img tag (<img src="/images/myimage.jpg" data-src="/images/myimage.png" alt="Example image" />) in the $img variable saved? Because my HTML code contains except img tags, other tags too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.