Jay Rizzi
Jay Rizzi

Reputation: 4304

JavaScript pass object into function by another function

Let me preface this as saying this is not the way I wanted to code the functions (inline and hijacks), but I have to work around a third party app config interface, with altering the source code as a final option.

So I have an image that calls an onclick function:

 <img src="images/button_closed.gif" id="img100023" border="0" 
  onclick="OnNodeImageClick(event, this)" href="theurl.cfm">

The function takes the vars event, this and gets the URL:

 function OnNodeImageClick(evt, clickedImage) {
    var href = clickedImage.getAttribute("href"); 
  ...

I need to do this exact same logic on a separate element that shares the original's id numbers:

 <span id="node100023" >External Links</span>

What I have tried is this as the html:

 <span id="node100023" 
  onclick="javascript:OverwriteToTreeHandler($(this).attr('id'))">
  External Links</span>

and this as my function:

 function OverwriteToTreeHandler(nodeID){
    var clickedItem = 'img'+nodeID.replace(/[^0-9]/g, '');  
        //tried $('body').find( clickedItem ) didnt work 
     OnNodeImageClick(event, clickedItem );
}

But I receive the following error:

Uncaught TypeError: Object img100023 has no method 'getAttribute'

However by statically assigning the identifier in the HTML.

What I have tried is this as the html, I get exactly the result I want:

 <span id="node100023" 
  onclick="javascript:OnNodeImageClick(event, img100023)">
  External Links</span>

I assume this has to do with the parameters, and the fact when I attempt to dynamically get the element, it is not registering it as an object, but I am not connecting on how this is done.

Upvotes: 0

Views: 246

Answers (1)

jbabey
jbabey

Reputation: 46647

OnNodeImageClick is expected a DOM element - you are passing a string. Try this:

function OverwriteToTreeHandler(nodeID) {
    var clickedItem = document.getElementById('img'+nodeID.replace(/[^0-9]/g, ''));

    OnNodeImageClick(event, clickedItem);
}

Also, this.id is preferable (performance and clarity wise) to $(this).attr('id') when you call OverwriteToTreeHandler.

Upvotes: 3

Related Questions