Convert simple jQuery to plain JavaScript

I'm having problem trying to convert this piece of code from jQuery into pure JavaScript.

The script is

if($('#item-1').find('#player').length == 1)
{
    innerHTML = "You Won!!!";
} else {
    innerHTML = "You Lose!!!";
}

Do I have to use getElementById?

if(document.getElementById("#item-1 #player").length == 1)

Answers 1

  • Use querySelector :

    //evaluates to true if length > 0
    if(document.querySelectorAll('#item-1 #player').length)
    {
        innerHTML = "You Won!!!";
    } else {
        innerHTML = "You Lose!!!";
    }
    

    or in 1 line code :

    var innerHtml = document.querySelectorAll('#item-1 #player').length ? 'You Won!!!' : 'You Lose!!!';
    

Related Articles