Feedster project .html() against .innerHTML


#1

https://www.codecademy.com/paths/web-development/tracks/learn-jquery/modules/learn-jquery-event-handlers/projects/feedster

Hi! On step 10, they ask you to use .html() to access the html text inside .characters

$(’.characters’).html(remaining);

Why before it was always asked us to access inner HTML with .innerHTML? What is the difference? is one for vanilla JS and the other for jQuery?


#2

seems you already answered your own question:

http://api.jquery.com/html/
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML


#3

so it wouldn’t work with:

$('.characters').innerHTML = remaining ?

Or it would work but is bad practice


#4

i don’t think its that straight forward:

http://mundrisoft.com/tech-bytes/jquery-html-vs-append-vs-innerhtml-difference-and-performance/


#5

The main diffrence between .innerHTML and .html() is:

.html() will change the html in all elements that are pointed to. So if you use this on multiple elements using class it will change all these elements.

.innerHTML is used on a single element. and can only be used with Javascript. This also does not seem to work when grabbing the element with Jquery.

Here are the tests i did to come to this conclusion.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src=""></script>
</head>
<body>
<p class="testhtml"></p>
<p class="testhtml"></p>
<p class="testhtml"></p>
<p class="testhtml"></p>

<p class="testinnerhtml"></p>
<p class="testinnerhtml"></p>

<p id="testinnerhtmlID"></p>

<p id="testinnerhtmlJS"></p>

<script>

$( ".testhtml" ).html( "Use of html()" );

// test applying .innerHTML using ID
$( "#testinnerhtmlID" ).innerHTML = "Use of innerhtml on ID" ;

// test applying .innerHTML using class
$( ".testinnerhtml" ).innerHTML = "Use of innerhtml" ;

// test grabbing element with jquery and applying .innerHTML
var element = $( ".testinnerhtml" )
element.innerHTML = "Use of innerhtml" ;

// test grabbing element with Javascript and applying .innerHTML
var elementJS = document.getElementById('testinnerhtmlJS');
elementJS.innerHTML = "Use of innerhtml using JS" ;

</script>
</body>
</html>

#6

thanks so much for this explanation! very clear and thorough!