user656925
user656925

Reputation:

.innerHTML vs. createElement() | setAttribute() vs. Direct*

I was told this was not "proper", I did not worry about it until I started getting a run-time error in IE9. Here is the code I need converted to use object properties. Why is innerHTML not considered best practice?

  var c=document.createElement('div');
  c.innerHTML= '<a name="a1" class="b" href="' + d[2].value + '">' + d[1].value + '</a>';

Upvotes: 6

Views: 15971

Answers (3)

The Surrican
The Surrican

Reputation: 29856

innerHTML is perfectly fine, you are just not using it correctly.

innerHTML targets the content of a tag. meaning what's between <a> and </a>

you need to set your d[2].value with setAttribute and only d[1].value with innerHTML

this should be fine (untested)

  var c=document.createElement('a');
  c.setAttribute("href",d[2].value);
  c.setAttribute("name","a1");
  c.setAttribute("class","b");
  c.innerHTML = d[1].value;

check these references and examples for setAttribute (method) and innerHTML (property)

Upvotes: 5

legendofawesomeness
legendofawesomeness

Reputation: 2911

It looks like you are creating an anchor - by using document.createElement('a') - and then creating another anchor within it. So, basically your HTML is going to look like this:

<a>
    <a href="www.google.com">Click Here</a>
</a>

This is not right. This is the reason why using innerHTML for anchors is not good. I think you should do it as follows:

c.setAttribute('class', 'signature'); 
c.setAttribute('href', 'xyz');

and so on.

You can also set the href and other attributes directly on the anchor using javascript. See http://www.w3schools.com/jsref/dom_obj_anchor.asp (Anchor object properties).

Upvotes: 2

Mike Samuel
Mike Samuel

Reputation: 120496

It's strange that you're putting an A element inside an A element but the below should work.

var c=document.createElement('a');
c.name = "a1";
c.className = "b";
c.href = d[2].value;
c.appendChild(document.createTextNode(d[1].value));

This assumes that d[1].value is not known to be well formed HTML from a trusted source so it is likely to be more robust against XSS than the innerHTML code.

Upvotes: 5

Related Questions