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.
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.
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.
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.
if(data && data != "") alert(data); data will be null in your case, and null != "" , so the if is passing.
$(".child:not(:empty)").prepend('<h1>title</h1>');
jQuery empty selector
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With