I have an array:
let ids = ["d0","d1","d2","d3","d4","d5","m0","m1","m2","m3","m4","m5"];
I have a bunch of html elements with id's that match the strings in the array.
<button id="d0" onclick="showMe(this);"> //etc etc... all the way to m5
I compare them with
function showMe(element){
var whoWasClicked = element;
let ids = ["d0","d1","d2","d3","d4","d5","m0","m1","m2","m3","m4","m5"];
for (let i = 0; i < ids.length; i ) {
if (whoWasClicked.id != document.querySelector(ids[i])) {
//document.querySelector(ids[0]).style.border = "none";
console.log(ids[i] " : " whoWasClicked.id);
}
}
}
I then get the following output:
d0 : d1
d1 : d1
d2 : d1
d3 : d1
d4 : d1
d5 : d1
m0 : d1
m1 : d1
m2 : d1
m3 : d1
m4 : d1
m5 : d1
They are both of type "string", so how is it possible to see
d1 : d1
as an output? shouldnt d1 not be shown and all the others be shown?
CodePudding user response:
document.querySelector(ids[i])
doesn't return a string, it returns an html element
You probably meant:
document.querySelector(ids[i]).id
document.querySelector
also matches the id only if it starts with #
otherwise it will try to find a tag so
document.querySelector('#' ids[i]).id
or
document.querySelector(`#${ids[i]}`).id
CodePudding user response:
Here's how you can compare two simple strings.
To compare two simple strings, you can use the comparison operators such as == (equal to), != (not equal to), > (greater than), < (less than). For example, if you wanted to compare two strings "Hello" and "World", you could use the == operator to check if they are equal:
if ("Hello" == "World") {
// Do something
}
Use the Array.prototype.includes() method to check if the array contains a given string.
Use the String.prototype.localeCompare() method to compare two strings and determine which one comes first in alphabetical order.
Use the Array.prototype.sort() method to sort the array in alphabetical order, and then use the Array.prototype.indexOf() method to find the index of each string in the sorted array.
Finally, compare the two indices to determine which string comes first in the array.