jQuery Modify Anchor Text after inserting it into a div

146 views Asked by At

I have the following problem.

I need to modify the anchor text after is added dinamically inside a div.

In my code:

The "Load file" button add the file loaded link in the div class = "div" (it's a simulation). The program that loads the file can't be modified.

That program returns the Anchor text with path and file name, but I just want to keep the name.

The problem is that I don't find in which event put my code to modify the anchor text. I did a test and it works with the mousemove event, but is just a test.

How to trigger the code that modify the anchor text?

The code below not works, but you can try enabling the mousemove event to see the desired result.

Thanks in advance! for your help...

$(document).ready(function () {
    $("#btnSave").click(function () {
          // alert("Alert  Click");
     $('.div').append(
            '<a id="link-x" href="http://example.com/file-3.pdf">http://example.com/file-3.pdf</a><br>');
 });
  
/*    This Works only for Testing
    $(document).mousemove(function () {
        $('a[id*="link"]').each(function(){
            var text = $( this ).text();
            var html = $( this ).html();
            var res = text .replace( 'http://example.com/', '' );
            $( this ).text( res );
        });
 });
*/    
    $('a[id*="link"]').on(function () {
        $('a[id*="link"]').each(function(){
            var text = $( this ).text();
            var html = $( this ).html();
            var res = text .replace( 'http://example.com/', '' );
            $( this ).text( res );
        });
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="mycode">
<button id="btnSave">Load File</button>
</div>
<div class="div">
<a id="link-x" href="http://example.com/file-1.pdf">file-1.pdf</a><br>
<a id="link-x" href="http://example.com/file-2.pdf">file-2.pdf</a><br>
</div>

1

There are 1 answers

6
Michał Perłakowski On

Try this:

$(document).ready(function () {
    $("#btnSave").click(function () {
        $('[id*="link"]').text(function() {
            return $(this).text().replace("http://example.com/", "");
        });
    });
});

Fiddle.