Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

311
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda