简体   繁体   中英

Swapping dynamically between text and data-text with vanilla JS

I'm trying this code to switch dynamically my text in an announcement bar.

 window.addEventListener('DOMContentLoaded', function(){ let text1 = document.querySelector("text1"); function changeText( ) { if (text1.getAttribute("data-text2") == text1.innerHTML) { text1.innerHTML = text1.getAttribute("data-text1"); } else { text1.setAttribute("data-text1", text1.innerHTML); text1.innerHTML = text1.getAttribute("data-text2"); } window.setTimeout(function() { changeText() }, 3000); } })
 <span class="text1" data-text2="Livraison gratuite partout au Canada.">Le Tero et Tero Plus en vente maintenant.</span>

Anybody can tell me what I'm doing wrong? Thanks!

Often times, especially with innerHTML you need to trim() your strings for comparisons, like:

text1.getAttribute("data-text2") == text1.innerHTML.trim()

 window.addEventListener('DOMContentLoaded', function(){ let text1 = document.querySelector("text1"); function changeText( ) { if (text1.getAttribute("data-text2") == text1.innerHTML.trim()) { text1.innerHTML = text1.getAttribute("data-text1"); } else { text1.setAttribute("data-text1", text1.innerHTML.trim()); text1.innerHTML = text1.getAttribute("data-text2"); } window.setTimeout(function() { changeText() }, 3000); } })
 <span class="text1" data-text2="Livraison gratuite partout au Canada.">Le Tero et Tero Plus en vente maintenant.</span>

First, you didn't select your element correctly. let text1 = document.querySelector(".text1"); you should use .text instead of text .

Second, you have some syntax error in your code, the curly bracket is not well placed.

 window.addEventListener("DOMContentLoaded", function () { let text1 = document.querySelector(".text1"); function changeText() { if (text1.getAttribute("data-text2") == text1.innerHTML) { text1.innerHTML = text1.getAttribute("data-text1"); } else { text1.setAttribute("data-text1", text1.innerHTML); text1.innerHTML = text1.getAttribute("data-text2"); } } window.setTimeout(function () { changeText(); }, 3000); });
 <span class="text1" data-text2="Livraison gratuite partout au Canada.">Le Tero et Tero Plus en vente maintenant.</span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM