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

I was told that this is not β€œcorrect”, I did not worry about it until I started getting a runtime error in IE9. Here is the code I need to use the properties of the object. 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>';
+5
source share
3 answers

It is strange that you place an element Ainside an element A, but the following 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 suggests that d[1].value, as you know, HTML is not well-formed from a trusted source, so it is more likely to be more XSS resistant than code innerHTML.

+4
source

innerHTML , .

innerHTML . <a> </a>

d[2].value setAttribute d[1].value innerHTML

()

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

setAttribute () innerHTML ()

+5

, - document.createElement('a') - . , HTML :

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

. innerHTML . , :

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

..

href , javascript. . http://www.w3schools.com/jsref/dom_obj_anchor.asp ( ).

+2

All Articles