Search code examples
javascripthtmlreplacegreasemonkeyswap

Swap title and tag using javascript


I have html code in a 3rd party website:

<div class="info_texts">
  <a href="down.php?action=details&amp;id=111"
  onclick="get_file(111); return false;"
  title="TOO LONGER TEXT, TOO LONGER TEXT, TOO LONGER TEXT, TOO LONGER TEXT, TOO LONGER TEXT, TOO LONGER TEXT, TOO LONGER TEXT">

    <nobr>TOO LONGER TEXT, TOO LONGER TEXT, TOO...</nobr>
  </a>
</div>

Now I see truncated text (Short text...) without whole of text (Full text, without ...)

I wanna swap title="" with <nobr></nobr> with javacript (greasemonkey script)

In website have a lot of <div class="info_texts"> so should replace all of tags.

Thank you!


Solution

  • Here is an example code:

    // get all a tags with title inside div info_texts
    var a = document.querySelectorAll('div.info_texts a[title]');
    
    // loop through them
    for (var i = 0, len = a.length; i < len; i++) {
    
      // use one of these
      // --------------------------------
    
    
      // 1- replaces the entire content including <nobr>
      a[i].textContent = a[i].title; 
    
    
      // 2- if you want to keep <nobr>
      var nobr = a[i].querySelector('nobr');
      if (nobr) { nobr.textContent = a[i].title; }
    
    
      // 3- combination of both above methods
      var nobr = a[i].querySelector('nobr');
      if (nobr) { nobr.textContent = a[i].title; }
      else { a[i].textContent = a[i].title; }
    
    
      // 4- more error checking, in case title is blank
      if (!a[i].title.trim()) { continue; }
      var nobr = a[i].querySelector('nobr');
      if (nobr) { nobr.textContent = a[i].title; }
      else { a[i].textContent = a[i].title; }
    }