I know how to show data-attribute value inside any tag. But how can I apply if else conditions to show text ?
For example, if there is data-attribute with value, then it will be display. But if there’s no data-attribute found, the default text will be display.
Here’s my simple code.
<h2 id="text" data-text="A Data Text Message"></h2>
<script type="text/javascript">
let message = document.getElementById("text").getAttribute("data-text");
/* If data-text attribute found with value, then this message will be show*/
// document.getElementById("text").innerHTML = message;
/* Otherwise this default message will be display*/
document.getElementById("text").innerHTML="A Data Text Messages";
</script>
>Solution :
let message = document.getElementById("text").getAttribute("data-text");
if (message) {
document.getElementById("text").innerHTML = message;
} else {
document.getElementById("text").innerHTML="A Data Text Messages";
}
<h2 id="text" data-text="A Data Text Message"></h2>
You just need to check if the message variable is truthy. If the data-text attribute has a value, it’ll be truthy, if it doesn’t, it won’t be.