开发者

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

I was told this was not "proper", I did not wo开发者_StackOverflow中文版rry 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>';


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.


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)


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜