0

I have the following HTML and I am trying to figure out how I can do something jQuery. I want to take the following and only do the following two lines of code if it can find a table with an id of myDatatable on the page. How would I right this I think it would be to trickle back to the parent and then try and do a find() but I'm not sure how I would right the conditional for it.

$('.panel-title').addClass('pull-left');
$('.panel-heading').append('<div class="pull-right" style="padding-top:5px;"><a class="btn btn-sm btn-default btn-block" href="'+ window.location.href +'/create">Add New</a></div>');

<!-- Begin: Content -->
<section id="content">
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-visible">
                <div class="panel-heading">
                    <div class="panel-title hidden-xs">
                        <span class="glyphicon glyphicon-tasks"></span>Users
                    </div>
                </div>
                <div class="panel-body pn">
                    <table class="table table-striped table-bordered table-hover" id="myDatatable" cellspacing="0" width="100%">
                    ...table data here
                    </table>
                </div>
            </div>
        </div>
    </div>
</section>
user3732216
  • 1,579
  • 8
  • 29
  • 54

1 Answers1

2

Just check if there is any table on the page with id=myDatabase

<!-- Begin: Content -->
<section id="content">
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-visible">
                <div class="panel-heading">
                    <div class="panel-title hidden-xs">
                        <span class="glyphicon glyphicon-tasks"></span>Users
                    </div>
                </div>
                <div class="panel-body pn">
                    <table class="table table-striped table-bordered table-hover" id="myDatatable" cellspacing="0" width="100%">
                    ...table data here
                    </table>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
    if($('#myDatatable').length>0){
        $('.panel-title').addClass('pull-left');
        $('.panel-heading').append('<div class="pull-right" style="padding-top:5px;"><a class="btn btn-sm btn-default btn-block" href="'+ window.location.href +'/create">Add New</a></div>');
    }

</script>

Also you can use has function of jQuery like this:

if($('#content').has('#myDatabase').length>0){
    $('.panel-title').addClass('pull-left');
    $('.panel-heading').append('<div class="pull-right" style="padding-top:5px;"><a class="btn btn-sm btn-default btn-block" href="'+ window.location.href +'/create">Add New</a></div>');
}
Mohi
  • 1,776
  • 1
  • 26
  • 39