Reputation: 9
<div class="header1">
sth
<span>
::before
sth2
</span>
</div>
<div class="pure-menu-link">
sth2
</div>
<script type="text/javascript">
var titleToHide = $('.header1 span').html();
titleToHide = titleToHide.replace('::before', '');
titleToHide.trim();
var titleToCompare = $('.pure-menu-link').html();
titleToCompare.trim();
if (titleToHide === titleToCompare){
$('.pure-menu-link').hide();
};
</script>
I'm trying to compare contents of span inside header1 and pure-menu-link, i need to hide p-m-l element when header1 is empty. Why it doesn't work?
Upvotes: 0
Views: 27
Reputation: 337560
The issue is due to the whitespaces differences between the two html()
values. trim()
is the right method to use to get rid of any extraneous whitespace before comparing, but you need to update your variables with its output, like this:
var titleToCompare = $('.pure-menu-link').html();
var titleToHide = $('.header1 span').html().replace('::before', '');
// note the whitespace difference in the console...
console.log(titleToHide);
console.log(titleToCompare);
// use trim() to fix this
titleToHide = titleToHide.trim();
titleToCompare = titleToCompare.trim();
if (titleToHide === titleToCompare) {
$('.pure-menu-link').hide();
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header1">
sth
<span>
::before
sth2
</span>
</div>
<div class="pure-menu-link">
sth2
</div>
Upvotes: 2