最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Change image alt with Javascript onclick - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a comment  | 

3 Answers 3

Reset to default 8

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.

发布评论

评论列表(0)

  1. 暂无评论