Change image alt with Javascript onclick
I have a thumbnail image that when clicked changes a larger imag开发者_运维知识库e 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?
You 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.
精彩评论