-4

i wrote a sample Html page that contain a img and change src of img with code

<img id='p6'/>

document.getElementById('p6').src='somting.jpg';

when i write code in tag find that i can write this code instead of above code:

p6.src='somting.jpg';

and it work perfectly...can anyone say to me what happend in this code? and realy we can access Html element whitout use document.getElementById() ?

Ali
  • 3,373
  • 5
  • 42
  • 54

2 Answers2

0

Here:

p6.src='somting.jpg';

p6 is a reference var to the actual dom node with id of p6, something like:

var p6 = document.getElementById('p6');
    p6.src='somting.jpg'; // now on you can use p6 as a ref. to the img

You can also use it when you create dynamic dom nodes:

var p6 = document.createElement('img');
    p6.id = "p6";
    p6.src = "some/path/to/img.ext";

    document.body.appendChild(p6);
Jai
  • 74,255
  • 12
  • 74
  • 103
  • and realy dont use var document.getElementById('p6')? – Ali Sep 08 '15 at 09:58
  • can you create a demo where you see it working without defining? – Jai Sep 08 '15 at 10:01
  • in create dynamic dom is ok and becuase we define p6 before can access it but access all element without document.getElementById is Interesting and useful – Ali Sep 08 '15 at 10:03
  • @combo_ci If you have this var in any js file go and find the var. – Jai Sep 08 '15 at 10:06
0

if you use the jQuery library, you can put :

$("#p6").attr('src', 'somting.jpg')
Slim Tekaya
  • 337
  • 3
  • 16