Home > Net >  do not output specific div if something is null using jquery
do not output specific div if something is null using jquery

Time:02-13

I am making database query.

let link = something from the database;
let output = `
   <div>
      ...
   <div>
   <div>
      ...
   <div>
   <div>
      <iframe src="${link}"></iframe>
   </div>
   <div>
      <div>
         ...
      </div>
   <div>
`;
$('#table').html(output);

The link could be empty then I do not want to output the highlighted div. I do not know a "cool" way of doing that.

CodePudding user response:

Consider the following.

$(function() {
  var links = [
    "Url 1",
    "",
    "Url 3",
    "Url 4",
    "Url 5"
  ];

  $.each(links, function(i, link) {
    if (link != "") {
      $("<div>").html($("<iframe>", {
        src: link
      })).appendTo("#table");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table">
</div>

You will want to iterate your data and conditionally add the HTML.

See More:

CodePudding user response:

If I understand your question correctly, you don't want to display the iframe, if link is set to null.

This is one of many ways how you could do it:

let link = 'Change me to null';
link ??= `
   <div>
      <iframe src="${link}"></iframe>
   </div>
`;

let output = `
   <div>
      ...
   <div>
   <div>
      ...
   <div>
`;
output  = link;
output  = `
   <div>
      <div>
         ...
      </div>
   <div>
`;
$('#table').html(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table"></div>

  • Related