2

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)

2 Answers 2

2

getElementById accepts the ID of single element without #. You need querySelector.

document.querySelector('#item-1 #player').length

Also, as ID is unique there is no need of descendant selector. The ID of the element can directly be used.

document.getElementById('player')

Code:

innerHtml = document.getElementById('player') ? 'You won!!!' : 'You lose!!!';

More complex:

innerHtml = 'You ' + (document.getElementById('player') ? 'won' : 'lose') + '!!!';
Sign up to request clarification or add additional context in comments.

1 Comment

"Also, as ID is unique there is no need of descendant selector." actually given the code it's likely that one element may be within the other at different times (it's very easy to move DOM nodes), which would mean that document.querySelector('#item-1 #player') would be appropriate for checking state, where document.getElementById('player') would not.
0

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!!!';

1 Comment

document.querySelector will return a single node. document.querySelectorAll will return a collection of nodes. The former doesn't have a length property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.