javascriptjqueryfunctionsetattributegetattr

how to use setAttribute when attr value is not available?


I have created code where I use setAttribute which works fine but the problem occurs when I remove the attr value. Let me explain an example with code

here is the code

//var darkImage = document.querySelector('#darkroom1'); 

// (localStorage.getItem('mode')) === 'darkmode' ? darkImage.setAttribute('src', darkImage.getAttribute('data-dark')): darkImage.setAttribute('src', darkImage.getAttribute('data-normal'))

//I use local storage also to save that dark logo click


 $(".dark-toggle").click(function() {
 document.querySelector('#darkroom1').setAttribute("src", document.querySelector('#darkroom1').getAttribute("data-dark"));
 });
 
 // this code works fine but when I remove data-dark attribute then why src='null' error cause
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img id='darkroom1' data-dark="https://ssl.gstatic.com/ui/v1/icons/mail/rfr/logo_gmail_lockup_dark_1x_r4.png" data-normal="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" height="73" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" width="321"/>


<div class='dark-toggle'>Click Me</div>

This code works fine but when I remove data-dark attribute then why src='null' error cause is there any solution available so that when we remove data-dark="" the code should take the data-normal value when data-dark attribute is not available

Any kind of help is highly appreciated


Solution

  • You can do like this

    $(".dark-toggle").click(function() {
      const target = $('#darkroom1');
      target.attr("src", 
        target.data("dark") 
        || target.data("normal"));
    });