skip to Main Content

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


  1. 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:

    if ( parentEl === localStorage.getItem('contentid') ) {
    

    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:

    localStorage.setItem('contentid', 'test'); // Save to LS
    
    
    $('button').on('click', function(){
    
        const $parent = $(this).closest('.parent'); // Get button's closest DIV by class ".parent"
        if (!$parent.length) return; // No such .parent was found. Do nothing
        
        const id = $parent.attr("id");
        const idLS = localStorage.contentid;
        
        if(id === idLS) {
          console.log("Parent ID is: 'test'");
        } else {
          console.log(`Parent ID is: ${id}`);
        }
    });
    
    <div class="parent" id="test">
      Some parent wrapper
      <button type="button">Click me</button>
    </div>
    
    Login or Signup to reply.
  2. $('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('can't go next');
        } else {
            console.log('go next');
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search