I need to validate a div element ID with the localstorage value. If true I need to show an error message. When I console.log the value of each they are the same, but when I console.log to compare both it returns false.
I don’t know what I am doing wrong.
<div id="test"></div>
$('button').on('click', function(){
var parentEl = $('div').attr('id');
localStorage.setItem('contentid', 'test');
if($(parentEl) == localStorage.getItem('contentid')) {
console.log('id === localstorage', $(parentEl) == localStorage.getItem('contentid'));
console.log('local', localStorage.getItem('contentid'));
console.log('id', parentEl);
console.log('cant go next');
} else {
console.log('go next');
}
});
2
Answers
As I said in comments, you cannot compare Object with a localStorage returned String value. so instead of
$(parentEl) == localStorage.getItem('contentid')
use the actual ID string:Why would you want to on every button click set all over again the same localStorage value to "test" ?
localStorage.setItem('contentid', 'test');
seems quite odd.What is
var parentEl = $('div').attr('id');
?$('div')
can be just any DIV in your document. You need to select a specific one like a button’s parent?In such case use: