Reputation: 141
I need to compare two divs for the same number then do something
I am using .is function
jQuery(function ($) {
if ( $("#result").is(".count-entries") ) {
alert("true");
}
});
<div class="count-entries">2</div>
<div id="result">2</div>
The alert isn't firing when the numbers are the same in the divs
Upvotes: 0
Views: 918
Reputation: 853
You are thinking of checking the .text()
of the divs, to see if they match.
if ($("#result").text() == $("count-entries").text()) {
alert("true");
};
Checking the actual content is not a good way of checking values, as any function which gets that info, returns the contents as a string, and if any space characters are included in only one of the two, the strings will not be equal, and it would not evaluate to true.
Give more info about your use case, and we will be able to provide better guidance.
Upvotes: 0
Reputation: 73
$(function () {
var entries=$(".count-entries").val(); /*To get the value*/
var result=$("#result").val();
if ( entries==result ) {
alert("true");
}
});
<div class="count-entries">2</div>
<div id="result">2</div>
:D
Upvotes: 0
Reputation: 26844
If you want to check if 2 divs have the same content, you can get the text of the div using text()
, use trim()
to remove extra spaces.
Note: .count-entries
is a class, there could be multiple elements with this class. You might need to specify the id
if that is the case.
if ($("#result").text().trim() === $(".count-entries").text().trim()) {
console.log("Content is the same");
} else {
console.log("Content is not the same");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="count-entries">2</div>
<div id="result">2</div>
Upvotes: 1