How to call a JS variable for an HTML h1

5

I have this little FIDDLE to exemplify my problem.

HTML

  <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>

    <h1>"I have " + count + " list items"</h1> 

JAVASCRIPT

var count = 0;

$("li").each(function(){
      count++;      
    });

The variable count of JavaScript will have the number of li 's ul .

How do I get the h1 variable to appear in count of HTML?

    
asked by anonymous 24.04.2015 / 13:17

3 answers

9

Or you fill in the <h1> integer, like this:

var count = 0;

$("li").each(function(){
    count++;      
});
$('h1').html("I have " + count + " list items");

Or create a span inside to save only count :

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>

<h1>I have <span>0</span> list items</h1> 
var count = 0;

$("li").each(function(){
    count++;      
});
$('h1 span').html(count);

And, as @KaduAmaral said, nor does it require each to do this count, you can solve everything in a row, taking the size ( length ) of the collection of <li> s:

$('h1 span').html( $('li').length );

If you want to do pure JavaScript instead of jQuery, it's also pretty simple:

var lis = document.querySelectorAll('li');
var span = document.querySelector('h1 span');
span.innerHTML = lis.length;
    
24.04.2015 / 13:20
3

One possible solution is to send the code / text you want for your h1 :

var count = 0;

$("li").each(function(){
      count++;      
    });

$('h1').empty().append("I have " + count + " list items");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul><h1>"I have " + count + " list items"</h1>
    
24.04.2015 / 13:21
0

You can do it this way:

var count = 0;
$("li").each(function(){
  count++;      
});
$( "#varh1").html("I have "+count+" list items");

In which varh1 is the element ID h1

    
24.04.2015 / 14:17