Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Show Javascript data-attribute value in conditional statement

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading