Nathan
Nathan

Reputation: 786

Using jQuery to Insert Value Inside of Element, Not After

I'm using jQuery to calculate the file size of linked documents, using the snippet below. The code inserts the information wrapped in a span element after the a element. I'd like to insert it in the value of the a element instead. Is this possible?

Thanks!

js (source: http://jshidell.com/2010/09/20/show-document-file-size-using-jquery/)

<script>
  function hdrDetails(i, elm, cl) {
    cl = cl/1024;  //divide content-length by 1024 (KB)
    var sz = cl>1024?"MB":"KB";  //if cl is still big, set to MB
    cl = cl>1024?cl/1024:cl;  //if cl is still big, divide again
    var len = $(elm).eq(i).text().length;  //check the link's text length
    if(len > 0) {
      //add a file size
      $(elm).eq(i).after("<span> ("+cl.toFixed(2)+" "+sz+")</span>");
    }
  }
  $(function() {
    var elm="a[href$='.pdf'],"+ //only the file types we want
    "a[href$='.doc'],"+
    "a[href$='.ppt'],"+
    "a[href$='.xls'],"+
    "a[href$='.docx'],"+ //don't forget 2007 versions
    "a[href$='.pptx'],"+
    "a[href$='.mht'],"+
    "a[href$='.xlsx']";
    $(elm).each(function(i, e) {
      if (e.hostname && e.hostname == location.hostname) {
        $.ajax({
          type: "HEAD",
          url: $(this).attr("href"),
          complete: function(xhr, textStatus) {
          var cl=xhr.getResponseHeader("content-length");
          if(textStatus=="success") {
            var cl=xhr.getResponseHeader("content-length");
            hdrDetails(i, elm, cl); //call the calculation fn
          }else{
            $(elm).eq(i).after("<span> (file not found)</span>");
          }
        }
      });
    }
  });
});
</script>

Starting HTML:

<a href="ms0778.01.01.pdf" target="_blank" title="Anti-Defamation League of B’nai B’rith. 1966,1975.">[Digital Archival Object]</a>

After existing js:

<a href="ms0778.01.01.pdf" target="_blank" title="Anti-Defamation League of B’nai B’rith. 1966,1975.">[Digital Archival Object]</a><span> (1.49 MB)</span>

DESIRED affect:

<a href="ms0778.01.01.pdf" target="_blank" title="Anti-Defamation League of B’nai B’rith. 1966,1975.">[Digital Archival Object <span>(1.49 MB)</span>]</a>

Upvotes: 0

Views: 160

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382274

You could use this to insert the text just before last character of your link :

var $e = $(elm).eq(i);
var t = $e.text();
$e.html(t.slice(0, -1)+"<span> ("+cl.toFixed(2)+" "+sz+")</span>"+t.slice(-1));

Upvotes: 2

Related Questions