Comparing HTML text content with jQuery

I have a page where the specific divshows the identifier for the "system role" of the user as follows:

<div id="systemRoleIndicator" style="display: none;">
    <p>Z</p>
</div>

I can determine fine using jQuery, but I cannot use it for anything. For example, I never get a completion message in this code:

<script src="/scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    var role = $("#systemRoleIndicator").text();
    alert("Your role is: " + role); //displays proper value
    if (role == "Z") {
        alert("Code completed!");
    }
</script>

Why could this be? Am I missing something to compare strings?

+4
source share
1 answer

The text for #systemRoleIndicatorwill also return the start and end space next to the p node. which returns text " Z ", not "Z". You need to either compare with the text of the p element .:

var role = $("#systemRoleIndicator p").text();

#systemRoleIndicator:

var role = $("#systemRoleIndicator").text().trim();
+6

Source: https://habr.com/ru/post/1622052/


All Articles