JavaScript下判断元素是否存在

文章2019-04-101,112 人已阅来源:网络

1. JavaScript判断表单元素是否存在(1)

if ("periodPerMonth" in document.theForm) {
    return true;
} else {
    return false;
}

2. JavaScript判断表单元素是否存在(2)

if (document.theForm.periodPerMonth) {
    //存在
}

if (typeof(document.theForm.periodPerMonth) == "object") {
    //存在
}

3. JavaScript判断页面元素是否存在

if (document.getElementById("id")) {
    //存在
}

4. JavaScript判断表单是否存在

if (document.theForm) {
    //存在
}

5.用Jquery写脚本

if ($("#someID").length > 0) {
    $("#someID").text("hi");
}