0

I am trying to replace the below document.write with createElement.

document.write('<pt:core.html pt:tag="img" id="a" src="/abc.gif"/>');

As below -

document.createElement("a");
document.getElementById("a").innerHTML = "<pt:core.html pt:tag='img' id='a' src='/abc.gif'/>";
var c= document.getElementById("a").value;

I am getting document.getElementbyId is null or not an object in the line 2(where we use .innerhtml ). Your inputs are appreciated. thanks.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
user1257836
  • 309
  • 2
  • 5
  • 10

4 Answers4

1

You're creating an <a> element, not an element with an ID of "a".

Furthermore, you don't need to use document.getElementById() here at all, you can instead assign your document.createElement() to a variable and reference that instead:

var elem = document.createElement('a');

elem.innerHTML = ...
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
1

document.createElement("a"); creates an <a> element and then throws it away because you don't capture its return value.

document.getElementById("a") gets an element with id="a" from the document. Since it is returning null, there is no such element in the document.

You probably want something more like

var myAnchor = document.createElement("a");
myAnchor.innerHTML = ...

"<pt:core.html pt:tag='img' id='a' src='/abc.gif'/>", however, is not HTML.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0
var element = document.createElement("a");
element.innerHTML = "<pt:core.html pt:tag='img' id='a' src='/abc.gif'/>";
document.body.appendChild(element);
Ruslanas Balčiūnas
  • 7,310
  • 3
  • 24
  • 41
0

document.getElementById can't find the element until you append it to the DOM. You need to do something like:

var a = document.createElement("a");
a.innerHTML = "<pt:core.html pt:tag='img' id='a' src='/abc.gif'/>";
document.body.appendChild(a);

After this, you can use document.getElementById("a"). But document.getElementById("a").value is not a useful thing to do. .value is only meaningful for user input elements, such as text boxes, <select> menus, and checkboxes.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • what does this do - document.body.appendChild(a);. does this add the html tag to the body of the html. – user1257836 May 08 '15 at 21:33
  • Also, can you please explain the below - var aobj=document.all? document.all["a"] : document.getElementById?a: "" – user1257836 May 08 '15 at 21:36
  • Old versions of Internet Explorer don't have `getElementById`, they have an object called `document.all` that contains all the elements. So that code is designed to run with both old and new browsers. – Barmar May 08 '15 at 21:40
  • thanks. document.body.appendChild(a); - does this add the html tag contained in id("a") to the body of the html doing the job of document.write ? – user1257836 May 08 '15 at 21:43
  • Yes, that's what it does. – Barmar May 08 '15 at 21:45