简体   繁体   中英

How to check data present or not in html id

I have a HTML paragraph, if it is empty I want to show alert using jquery how.? I have tried the following:

 var abc= $("#foo").text(); var abc= $("#foo").data(); var abc= $("#foo").val(); if (abc== '') { alert('working'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="foo"></p> 

val() is used to retrieve the value of an input , not the text node value of an element. data() is used to retrieve data values for an element, not its text node value.

To check if the element does not contain anything , you should used text() . It's also worth noting that you may (or may not) need to use $.trim() to ignore whitespace, and to also check for child elements that do not have any text using children() :

 var $p = $('#foo'), empty = ($.trim($p.text()) == '' && !$p.children().length); console.log(empty); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="foo"></p> 


Better still though, rather than rolling your own function for this, you can use jQuery's is() function, coupled with the :empty selector:

 console.log( $('#foo').is(':empty') ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="foo"></p> 

try this :

var abc = $("#foo").text()
if(!abc) {
alert('not working');
} else {
    alert('working');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM