Hello!

Help, please, solve the problem by JS. You need to pull the variable "chosenClass" with its value from the function to continue working with it.

Thank you in advance.

---- JS ----

(function(){ var elements = document.querySelectorAll('.items > span'); for (var i = 0; i < elements.length; i++){ elements[i].onclick = function(){ document.getElementById('userResult').innerHTML = this.innerHTML; var chosenClass = this.childNodes[0].classList[3]; } } })(); 

https://jsfiddle.net/webEugene29/ot4men92/

Reported as a duplicate by Grundy , fori1ton , post_zeew , cheops , Bald members on Oct 25 '16 at 6:02 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

    You can declare this variable outside the function, i.e. So:

     var chosenClass = значениеПоУмолчанию; (function(){...})(); 

    either do so: window.chosenClass =... , and your variable will become global.

    • Thank you for your answer, but something still does not work. - webEugene
    • jsfiddle.net/webEugene29/6q8pwd99 - threw the code completely, perhaps the wrong place. It immediately returns null, but you need a value from the function. - webEugene
    • one
      You understand that until the function is called, there can be no "value from the function"? This means that instead of null you need to set a default value that will be used before the function changes your variable. - selya
    • If you set the default, the compare () comparison script will be processed immediately when the page is rebooted / loaded, and you need to be processed only after pressing the button: - webEugene
    • <button id = "play" onclick = "compare ()"> Play </ button> - webEugene