JQuery hides blank space in div
I want to hide the range that is in the div when it is null or undefined.
<div id="pricetag">1
<div class="price">400</div>
<span>hello</span>
<span>undefined</span>
</div>
So, I want to have at the end:
1
400
hello
I tried something like:
$("#pricetag").filter(function () {
return $('span', this).filter(function () {
return $(this).text().trim() == 'null' || $(this).text().trim() == 'undefined'
}).length;
}).hide();
But it does not work, it hides the entire div.
$("#pricetag").filter(function() {
return $('span', this).filter(function() {
return $(this).text().trim() == 'null' || $(this).text().trim() == 'undefined'
}).length;
}).hide();<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pricetag">1
<div class="price">400</div>
<span>hello</span>
<span>undefined</span>
</div>+4
2 answers
You need .filter()an element <SPAN>and hide()them.
$("#pricetag span").filter(function () {
return $(this).text().trim() == 'null' || $(this).text().trim() == 'undefined'
}).hide();
$("#pricetag span").filter(function() {
return $(this).text().trim() == 'null' || $(this).text().trim() == 'undefined'
}).hide();<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pricetag">1
<div class="price">400</div>
<span>hello</span>
<span>undefined</span>
</div>+3
You can use the selector :contains()to perform this task on a single line:
$('#pricetag span:contains(undefined),#pricetag span:contains(null)').hide();<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pricetag">1
<div class="price">400</div>
<span>hello</span>
<span>undefined</span>
</div>+3