简体   繁体   中英

Check if element contain something within

<p></p> // return true 

<p>something</p> //return false

I thought of using jquery's contains() but I think there's a better way of doing it in pure js?

return element.innerHTML.trim().length == 0;

You can use either childNodes or children in plain JS. Both return an array-like collection containing the children of an element. Both collections have a length property.

Note that both properties are live collections. You might want to shallow-copy them into an array. Here's an example of getting all children of body.

var hasContent = Array.prototype.slice.call(document.body.children).length;

I would use the old innerHTML to avoid JQuery like you want:

function hasSomething(id) {
    var element = document.getElementById(id);
    if (element && (element.innerHTML || '').trim())
        return true;
    else
        return false;
}

Assume you've got a tag with id mydiv

<p id='mydiv'>Something</p>

if($('#mydiv').is(':empty'))

or

if($('#mydiv:empty').length)

can check whether it's empty.

SOmething like:

var myTextField = document.getElementById('myText');
    if(myTextField.value != "")
        alert("nothing")
    else
        alert("Would you please enter some text?")      
}

Check function in the code below will do the job, You just need to call it. I have attached code in both jquery and javscript.

HTML :

<p id="data">Some text</p>

Jquery :

<script>
function check()
{
    var len= $("#data").text().length;
    if(len==0)
        return true;
    else
        return false;
}

$(document).ready(function(){
    document.write(check()); // call check function
});
</script>

Javascript:

<script>
function check() {
    var x = document.getElementById("data").innerHTML;
    if(x.length==0)
    return true;
else
     return false;

}
</script>

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