Search code examples
phpjqueryhtmltagsalt

php: Echo "alt tag" contents to "title tag"


Images in PHP files have an "alt" tag, but I need to duplicate its content to "title" tag. So the code automatically reads the page when it loads, and adds the new "title" tag beside the "alt" tag, whether using PHP, jQuery, JavaScript..

Example:

<img border="0" src="../../../../images/divider.jpg" alt="description of image" width="410" height="15">

Output:

<img border="0" src="../../../../images/divider.jpg" alt="description of image" title="description of image" width="410" height="15">

Solution

  • Using JavaScript, you can search <img> tags, and add this title attribute:

    let imgs = document.querySelectorAll('img');
    for (let i=0;i<imgs.length;i++) {
      if (!imgs[i].title) // if title is not defined
          imgs[i].title = imgs[i].alt;
    }
    

    Using jQuery, you can use find images $('img') and loop using each():

    $('img').each(function(img) {
      if (!this.title)
        this.title = this.alt;
    });