leykan
leykan

Reputation: 389

I can't get id of a image in javascript

I want to get the id of my img in javascript on a mousewheel but when I do a getElementById I it tells me that the length is null

this is the function where I put my img

function parse_data(data)
{
 var json = data;
 var obj = JSON.parse(json);
 var buff = "";

 for(var i in obj)
 {
  //document.write('<br>' + i + '<br>');                                                                                                                                                                                                 
  for (var j in obj[i])
  {
        if (obj[i][j] == true)
          buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_green.jpg\" border=\"0\" /></a>";
        else
          buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_gray.jpg\" border=\"0\" /></a>";
  }
    buff += "<br>";
 }
  document.getElementById('frisekk').innerHTML = buff;
}

And this is the function where I want to get back the id of an img on mousewheel

function test()
{
  var obj = document.getElementById('img');

  alert(obj.length); //obj.length is null...
  if (event.wheelDelta >= 120)
    unit -= 60;
  else
    unit += 60;
 request(readData);
}

how could I get the id of my img ?

there is all the html code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Techniques AJAX - XMLHttpRequest</title>
<script>
 var unit = 60;
 var date = 'Mon Oct 20 2014 19:25:00 GMT (CET)';

 function request(callback)
 {
  var xhr = getXMLHttpRequest();
  var frise = 600;
  var template = 'lab';

  xhr.onreadystatechange = function()
  {
   if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
    callback(xhr.responseText);
  };

  xhr.open("GET", "a.php?Frise=" + frise + "&Unit=" + unit + "&Template=" + template + "&Date=" + date, true);
  xhr.send(null);
}

function readData(sData)
{
 parse_data(sData);
}

function parse_data(data)
{
 var json = data;
 var obj = JSON.parse(json);
 var buff = "";
 for(var i in obj)
 {
   //document.write('<br>' + i + '<br>');                                                                                                                                                                                                                                                                                                
   for (var j in obj[i])
   {
      //document.write(j + "=" + obj[i][j] + '<br>');                                                                                                                                                                                                                                                                                   
      if (obj[i][j] == true)
        buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_green.jpg\" border=\"0\" /></a>";
      else
        buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_gray.jpg\" border=\"0\" /></a>";
    }
   buff += "<br>";
  }
  document.getElementById('frisekk').innerHTML = buff;
}

function test()
{
 var obj = document.getElementById('img');
 alert(obj.length);
 if (event.wheelDelta >= 120)
   unit -= 60;
 else
   unit += 60;
 request(readData);
}

</script>


<script>
function getXMLHttpRequest()
{
 var xhr = null;
 if (window.XMLHttpRequest || window.ActiveXObject) {
   if (window.ActiveXObject)
   {
     try 
     {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
     } 
     catch(e)
     {
      xhr = new ActiveXObject("Microsoft.XMLHTTP");
     }
    } 
    else 
    {
      xhr = new XMLHttpRequest();
    }
   }
   else 
   {
    alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
    return null;
   }
  return xhr;
 }
</script>
<span id="frisekk"> <br/> </span>
</head>
<body>
<form>
<p>
<input type="button" onclick="request(readData);" value="Exécuter" />
</p>
</form>
</body>
</html>

Upvotes: 0

Views: 1881

Answers (2)

somethinghere
somethinghere

Reputation: 17340

document.getElementById does not get the id for you, it gets the element by id passed. Since you didn't post your HTML I can't really say whether your <img /> tag has the id of img, but I'm assuming not. What you are looking for is document.getElementsByTagName('img') to get tevery img element on the page and then use a loop to find which one you need (or add [0] if you know you only have one to select the first element).

So you have two options:

  1. Add an ID to your element (best option)

<img src="path/to/image.jpg" id="my_image" /> var finalElement = document.getElementById("my_image");

  1. Find all elements with the tagname 'img' and then search through them for the right on

<img src="path/to/image.jpg" /> var elements = document.getElementsByTagName("img"); var finalElement = false; for(var i = elements.length -1; i >= 0; i--){ // match your element and return if(/* criteria */){ finalElement = elements[i]; break; } }

  1. Have only one image on your page and select that:

<img src="path/to/image.jpg" id="my_image" /> var finalElement = document.getElementsByTagName("img")[0];

Update

Your onmousewheel property could be supported, but then you need to do it slightly differently, because your link has the onmousewheel event.

<!-- add the 'this' keyword to your test() function to pass the <a> element -->
<a href="#" onmousewheel="test(this)"><img src="path/to/image.jpg" /></a>

With this structure (one <img> nested in an <a>), you can pass the <a> to the function using the thiskeyword.

/* Add a variable to receive your <a> in your test() function. */
function test(link){
    /* Use childNodes[0] to select the first child element of the a. */
    var image = link.childNodes[0];
    /* Will alert '1' if the <a> has a child, will alert '0' if the <a> is empty.*/
    alert(image.length);
}

Now you can easily access the only child of the a element, the image, and do something with that.

I am not sure whether onmousehweel is supported on an element, so pelase consider an onclick or onmouseover to test this function. If you decide to test with onmouseover, use the console.log to log instead of alert, otherwise you'll drown in alerts.

Upvotes: 2

pgee70
pgee70

Reputation: 3984

Can't you parse the id in the function call? Eg in:

onmousewheel=test(obj[i])

and in the function,

function test(id)??

Upvotes: 0

Related Questions