Home > Software engineering >  Show Javascript data-attribute value in conditional statement
Show Javascript data-attribute value in conditional statement

Time:12-21

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>

CodePudding user response:

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.

CodePudding user response:

You can apply if-else condition this way:

if (message == undefined || message.length == 0 ) {
    document.getElementById("text").innerHTML="A Data Text Messages";
  }
else{ 
    document.getElementById("text").innerHTML = message;
  }

CodePudding user response:

A simple way would be to use the conditional (ternary) operator ? :

If message is null or empty it will use the 2nd part of the operator...

// Example using attribute
setH2(document.getElementById("text"));

// Example using empty or missing attribute
setH2(document.getElementById("text2"));

function setH2(ctrl) {
  let message = ctrl.getAttribute("data-text");
  ctrl.innerHTML = (message ? message : "A Data Text Messages");
}
<h2 id="text" data-text="A Data Text Message"></h2>
<h2 id="text2"></h2>

You could also simplify this by using the nullish coalescing operator ??:

// Example using attribute
setH2(document.getElementById("text"));

// Example missing attribute
setH2(document.getElementById("text2"));

// Example EMPTY attribute
setH2(document.getElementById("text3"));

function setH2(ctrl) {
  let message = ctrl.getAttribute("data-text");
  ctrl.innerHTML = (message ?? "A Data Text Messages");
}
<h2 id="text" data-text="A Data Text Message"></h2>
<h2 id="text2"></h2>
<h2 id="text3" data-text=""></h2>

This checks if message is nullish - if it is, it uses whatever is after the ??, if it is not, it uses the message variable.

BUT NOTE this it does not recognise the empty attribute as being falsey.. so it will only work with a missing attribute

  • Related