user1302575
user1302575

Reputation:

Changing attribute of dynamically generated tags with JQuery

I have a requirement to rewrite src and/or href attribute of tags on a page using Jquery. I have tried this sample code. It works for tags which are already in the html page, however for tags dynamically generated by Javascript it does not work.

Any solution for this kind of requirement that every time tags are generated like img tag I need to change it's attribute.

Sample Code:

<script>
$("img").attr({ 
  src: "/images/hat.gif",
  title: "jQuery",
  alt: "jQuery Logo"
});
$("div").text($("img").attr("alt"));
</script>

Upvotes: 2

Views: 1283

Answers (2)

lukenz
lukenz

Reputation: 139

Try something like the following:

$('#id_of_element_to_change').attr("src")="path/src_or_href";

Upvotes: 0

What I see on your code is that you are generating the img element twice... you should keep the reference to the element you create the first time.

Like this:

<script>
var myImage = $("img").attr({ 
  src: "/images/hat.gif",
  title: "jQuery",
  alt: "jQuery Logo"
});
$("div").text(myImage.attr("alt"));
</script>

Upvotes: 1

Related Questions