Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add content if element is not empty

Tags:

jquery

HTML:

<div id="parent"> 
  <div class="child"></div> 
  <div class="child"><p>Div with content<p></div> 
  <div class="child"><img scr="pic.png" alt="Div with picture" /></div>
</div>

Result I want:

<div id="parent"> 
  <div class="child"></div> 
  <div class="child"><h1>title</h1><p>Div with content<p></div> 
  <div class="child"><h1>title</h1><img scr="pic.png" alt="Div with picture" /></div>
</div>

My jQuery code:

$(".child").each(function() {
    if ($(this).html != '')
        $(this).prepend('<h1>title</h1>');
});

Result with my jQuery code:

<div id="parent"> 
  <div class="child"><h1>title</h1></div> 
  <div class="child"><h1>title</h1><p>Div with content<p></div> 
  <div class="child"><h1>title</h1><img scr="pic.png" alt="Div with picture" /></div>
</div>

So I just want to add a title to every div of a certain class that's not empty.

like image 873
Puyol Avatar asked May 04 '12 12:05

Puyol


People also ask

How do I check if a div is not empty?

Use the childNodes property to check if a div element is empty. The childNodes property returns a NodeList of the element's child nodes, including elements, text nodes and comments. If the property returns a value of 0 , then the div is empty.

How do you check if an element is empty in HTML?

This method can be used on this element to test if it is empty by using “:empty” selector. The “:empty” selector is used to select all the elements that have no children. It will return true if the element is empty, otherwise, return false.

How do I check if a div has content?

To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.

How check data is empty in jQuery?

if(data && data != "") alert(data); data will be null in your case, and null != "" , so the if is passing.


1 Answers

$(".child:not(:empty)").prepend('<h1>title</h1>');

jQuery empty selector

like image 149
Evan Mulawski Avatar answered Oct 16 '22 18:10

Evan Mulawski