Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .html vs .attr('innerHTML')

Tags:

jquery

If i am setting the contents of a DIV element in my dom:

$("#myE").html(contents);

Is there ANY difference at all between the above and:

$("#myE").attr('innerHTML', contents);

? Thanks!

like image 777
PCC Avatar asked Dec 13 '22 10:12

PCC


2 Answers

The second option, will create an attribute (if it doesn't exist) called 'innerHTML' on the dom element with id 'myE' and set the value to contents. The first option will set the html content of the dom element with id 'myE' to whatever contents actually is.

The first option will result in

<div id="myE">
  whatever the value of 'contents' is
</div>

The second option will result in (if 'myE' is a div)

<div id="myE" innerHTML="whatever_contents_value_is">
...
</div>
like image 118
Joeblackdev Avatar answered Jan 25 '23 10:01

Joeblackdev


jAndy writes the following here: JQuery html() vs. innerHTML

.html() will just call .innerHTML after doing some checks for nodeType's & stuff. It also uses a try/catch block where it trys to use innerHTML first and if that fails, it'll fallback gracefully to jQuerys .empty() + append()

Hope this clarifies the situation.

like image 45
karllindmark Avatar answered Jan 25 '23 10:01

karllindmark