0

`

var questions = new Array($("#question1"), $("#question2"), $("#question3"))
var randomQuestion = questions.sort(() => .5 - Math.random());

console.log( randomQuestion[0] )
console.log(  $("#question3") )
if ( randomQuestion[0] === $("#question3") ){ alert("same")}
else { alert("unsame")} `

enter image description here

Why if randomQuestion[0] === $("#question3") not work ?

All condition still show alert unsame.

JMP
  • 4,417
  • 17
  • 30
  • 41
Shawn -
  • 109
  • 9
  • maybe because the sort is randomic? – niccord Oct 13 '20 at 09:03
  • Use `(randomQuestion[0]).is($("#question3"))` – Pranav Rustagi Oct 13 '20 at 09:04
  • 2
    It's because you cannot compare jQuery objects directly. You need to compare properties of the objects - ideally an `id` if available – Rory McCrossan Oct 13 '20 at 09:06
  • Why should it work? Even if `randomQuestion[0]` would contain the element with id `question3` you're comparing two distinct jQuery objects. This would only work with actual DOM nodes. – Andreas Oct 13 '20 at 09:07
  • 1
    More info on [object comparison](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – Reyno Oct 13 '20 at 09:07

3 Answers3

1

Just like I told in the comment section, use .is() to check if the elements are same or not :)

var questions = new Array($("#question1"), $("#question2"), $("#question3"))
var randomQuestion = questions.sort(() => .5 - Math.random());

console.log(randomQuestion[0])
console.log($("#question3"))

if ((randomQuestion[0]).is($("#question3"))) {
  alert("same")
} else {
  alert("unsame")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="question1">Question 1</div>
<div id="question2">Question 2</div>
<div id="question3">Question 3</div>
Pranav Rustagi
  • 2,604
  • 1
  • 5
  • 18
0

From what i know, you can't compare jquery objects, so try comparing DOM objects, like:

if (randomQuestion[0][0] === $('#question3')[0])
Johnny Tee
  • 216
  • 2
  • 10
0

$(something) creates a jQuery object. You are creating two identical jQuery objects, but object comparison doesn't care if objects are identical, only if they are the same object.

Compare DOM elements instead:

randomQuestion[0][0] === $("#question3")[0]

Or test the ID of the element:

randomQuestion[0]).is($("#question3")
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335