alex3025
alex3025

Reputation: 139

jQuery appends only if the div isn't empty

I have a div element and I want to append an icon to it on hover but jQuery appends the icon only if the div isn't empty else nothing happens.

$('div #tags').hover(function() {
  $(this).append('<p>+</p>')
}, function() {
  $(this).find("p").last().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tags">
  <p>The div isn't empty</p>
</div>

Upvotes: 0

Views: 145

Answers (3)

Mamun
Mamun

Reputation: 68933

Since the div and the id refers to the same element, you should not have any space in the selector in between them.

Please Note: Since the id attribute is unique in a document, simply $('#tags') is safe enough to target the element.

$('#tags').hover(function() {
  $(this).append('<i class="fa fa-plus-circle ml-1 add-tag-icon"></i>')
}, function() {
  $(this).find("i").last().remove();
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tags">
    <p>The div isn't empty</p>
</div>

jQuery appends the icon only if the div isn't empty else nothing happens.

If the div is empty there is nothing in the page on which you can hover. Please see the following example:

$('#tags').hover(function() {
  $(this).append('<p>+</p>')
}, function() {
  $(this).find("p").last().remove();
});
#tags{
  width: 100px;
  height: 15px;
  background-color: lightgray;
  border: 1px solid gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tags">
  
</div>

Upvotes: 2

Ritesh Khandekar
Ritesh Khandekar

Reputation: 4005

Height & width of <div> & <p> elements are by default 0, hence your hover effect wouldn't produce(you cannot hover on element):

<div id="tags"><p></p></div>

If you write some text inside element then width and height will change & you will able to produce hover effect:

<div id="tags"><p>Not empty</p></div>

Therefore <i> doesn't append if div or p elements are empty

Upvotes: 0

Mohab El-Sayed
Mohab El-Sayed

Reputation: 31

$('div #tags') is a wrong selecting for your <div> in your case. What you did means that jQuery is looking for an element with the id of #tags inside the <div>. Instead, you need to make it $('#tags').

Upvotes: 1

Related Questions