0

I'm currently working on a chrome extension that let the user click on a node to get its content. Getting the inner text is simple when using textContent, but getting the url of a picture in a clicked div...

I tried using this function to get the img node and thus being able to read its href/src:

function getimgtag(elem) //elem is the clicked div
{
    for(i=0;elem.getElementsByTagName('div')[i];i++)
    {
        getimgtag(elem.getElementsByTagName('div')[i]);
    }
    if(elem.getElementsByTagName('img')[0])
    {
        localStorage['fus_imgtag']=elem.getElementsByTagName('img')[0];
    }   

}

But it doesn't seems to have an end and I really don't understand why. Shouldn't it check all the div elements and place the last img found in localStorage['fus_imgtag']?

4
  • 1
    You forgot to declare i as in var i. Commented Jun 12, 2013 at 8:16
  • That's not the problem, but I would cache elem.getElementsByTagName('div') and elem.getElementsByTagName('img'). Calling it over and over again is a waste of resources. Commented Jun 12, 2013 at 8:17
  • @elclanrs: That's the answer :) Commented Jun 12, 2013 at 8:18
  • Glad it helped, I'll post as answer then. Commented Jun 12, 2013 at 8:36

1 Answer 1

2

You forgot to declare i as in var i. If you don't declare it, it becomes an implicit global variable which is always trouble particularly in your case where i should be scoped locally for every recursive call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.