Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

元素节点的判断 #10

Open
zlluGitHub opened this issue Apr 12, 2018 · 0 comments
Open

元素节点的判断 #10

zlluGitHub opened this issue Apr 12, 2018 · 0 comments

Comments

@zlluGitHub
Copy link
Owner

zlluGitHub commented Apr 12, 2018

为什么要判断元素的节点?

  • 因为要判断元素节点类型,因为属性的一系列操作与元素的节点类型息息相关,如果我们不区分它们,我们就不知道用元素的直接属性操作(例如:ele.xxx=yyy)还是用一个方法操作(el.setAttribute(xxx,yyy))。

  • 设计元素类型的判定,这里给出有4个方法:

  • (1). isElement :判定某个节点是否为元素节点

  • (2). isHTML :判定某个节点是否为html文档的元素节点

  • (3). isXML : 判定某个节点是否为xml文档的元素节点

  • (4). contains :用来判定两个节点的包含关系

元素节点的判定:isElement

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>isElement</title>  
</head>  
<body>  
    <div id="test">aaa</div>  
    <!--这是一个注释节点-->  
    <script>  
        var isElement = function (el){  
            return !!el && el.nodeType === 1;  
        }  
        var a = {            //随意定义一个变量,设置nodeType为1  
           nodeType: 1  
        }  
        console.log(isElement(document.getElementById("test")));   
        //结果:  true  
        
        console.log(isElement(document.getElementById("test").nextSibling));
        //这里的nextSibling属性查找下一个相邻节点,即注释节点  
        //结果:  false  
        
        console.log(isElement(a));  
        //结果:  true  
    </script>  
</body>  
</html>  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant