I have a thumbnail image that when clicked changes a larger image on the page. I have that part of the code working by just changing the .src with onclick. Is there also a way to change the alt and title attributes with onclick?
I have a thumbnail image that when clicked changes a larger image on the page. I have that part of the code working by just changing the .src with onclick. Is there also a way to change the alt and title attributes with onclick?
Share Improve this question asked Jul 10, 2010 at 20:14 computersauruscomputersaurus 1751 gold badge2 silver badges11 bronze badges3 Answers
Reset to default 8You can use setAttribute or set the property directly. Either way works, the setAttribute is the standard DOM way of doing it though.
el.onclick = function() {
var t = document.getElementById('blah');
// first way
t.src = 'blah.jpg';
t.title = 'new title';
t.alt = 'foo';
// alternate way
t.setAttribute('title', 'new title');
t.setAttribute('alt', 'new alt');
t.setAttribute('src', 'file.jpg');
}
In exactly the same way..
document.getElementById('main_image_id').title = 'new title'
document.getElementById('main_image_id').alt = 'new alt'
img.onclick = function() {
// old fashioned
img.src = "sth.jpg";
img.alt = "something";
img.title = "some title";
// or the W3C way
img.setAttribute("src", "sth.jpg");
img.setAttribute("alt", "something");
img.setAttribute("title", "some title");
};
Note: No matter which one you're using as long as you're dealing with standard attributes.