Can I get a number inside a square?

What I would like is when I click on the demo button it alerts me with a number inside a green (highlighted) square.

$('#demo').click(function() {
var x = document.getElementsByClassName('selected');
var numb = x[0].innerHTML;
alert(numb);
});

      

The problem is that I always get "1" as results and this is not what is expected ...

Thanks for your help!

+3


source to share


3 answers


You need to access the last item, not the first item. Also add the selected class to the first element by default:

$('#button').click(function() {
  var numb = $('.selected:last').text();
  alert(numb);
});

      



Working demo

+3


source


This is because you < remove the class selected

when you scroll up , otherwise it will keep the class.

When using JavaScript console

document.getElementsByClassName('selected');

[<li class=​"post selected">​1​</li>​, 
 <li class=​"post selected">​2​</li>​, 
 <li class=​"post selected">​3​</li>​, 
 <li class=​"post selected">​4​</li>​, 
 <li class=​"post selected">​5​</li>​]

      

You need to either fix your logic to remove all other classes selected

when adding a new one.



Or you can just select the last selected as I did in the following example using x.length - 1

var x = document.getElementsByClassName('selected');
var numb = x[x.length - 1].innerHTML;

      

http://jsfiddle.net/f3wqznek/1/

0


source


You get what you ask for.

On scrolling, you add a class .selected

to each li

one that exits the viewport. So when you do document.getElementsByClassName('selected')

, you end up with an array of DOM objects, which you always refer to first. Open the latter instead :

var x= document.getElementsByClassName('selected');
var numb = x[x.length-1].innerHTML;

      

0


source







All Articles