Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

310
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can do like this

$(".dark-toggle").click(function() {
  const target = $('#darkroom1');
  target.attr("src", 
    target.data("dark") 
    || target.data("normal"));
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!