0

After I replace IP address in innerHTML event listeners doesn't working.

My code:

$( "iframe" ).load(function() { 
   $("iframe").contents().find("b").html(function(_, html) { 
      return html.replace(/(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)/, '<a href="http://$1/" target="_blank">$1</a>');
   });
});

part of innerHTML in iframe

 <a id="go" rel="leanModal" name="test_2" href="#event">2</a> <!--this anchor loses event listener -->
    <li>
        <ul>
            <li>
                <b>MyRouter1 - 192.168.1.1</b>
            </li>
            <li>
                <b>MyRouter2 - 192.168.1.2</b>
            </li>
        </ul>
    </li>

How to make IP address clickable without replacing innerHTML or killing DOM elements / event listeners?

Kublach
  • 11
  • 4

1 Answers1

0

If you want to create event listeners that will continue to work even after the HTML changes, check out $.on(). You can use it to place a listener on the body which will fire when a child that matches a selector has an event. For example:

$("body").on("click", "a",function(event){ doSomething(); });

The above code will call its event handler any time an a tag is clicked. You can replace "a" with the selector for the element you want to listen on. It will continue to work even when the DOM is changed, because the listener is on body.

EDIT: It seems that you may be using javascript to edit an existing page that you did not create. In that case, it would be very difficult to edit the markup without breaking the event listeners that are in place, since you don't control how the event listeners were created. Also, this specific problem may be related to the fact that your replacement results in invalid markup, since you insert an a tag inside an existing a.

To Make an Element clickable without messing with inner html and also style it to make it clear that it is clickable:

$("b").click(function(event){
    //handle your click here
    //window.location = "http://someurlhere"
}).css({"color":"blue","cursor":"pointer"});
devinallenaz
  • 430
  • 3
  • 9