Get and set properties

The original property element: id class title style dir, etc.
<!DOCTYPE html>
<html>

 

<head>

 

</head>

 

<body>
    <div id="box" name="bird" title="其不知道啊" a="world">

 

    </div>

 

    <script>
        var div = document.querySelector('#box');

 

        1. The method of using getAttributes value // Get a property element node
        var res = div.getAttribute('title');
        console.log(res);

 

        2. Use // attribute nodes acquires the attribute value nodeValue
        var arr = div.getAttributeNode ( 'title'); // get property node
        console.log(arr);
        console.log(arr.nodeValue);

 

        // use dot syntax, attribute name element node;. (Common)
        console.log(div.title);
        console.log(div.name);//undefined

 

        // use of brackets, the element node [ 'attribute name']; (common)
        console.log(div['title']);
        console.log(div['id']);

 

        // Note: behind the dot syntax can not add variables, however, can be added back in parentheses variable
        var str = 'title';
        console.log(div.str);//undefined
        console.log(div[str]);
 
       // custom properties how to operate (temporarily not understood)
        console.log(div.getAttribute('a'));
        console.log(div.getAttributeNode('a').nodeValue);
        console.log(div.a);
        console.log(div['a']);


        // setAttribute method may be used to set property values,
        // Format: Node elements .setAttribute ( 'attribute name', 'attribute');
        console.log('------------------------------------------------');
        div.setAttribute ( 'title', 'I do not know if you just want to Moss ah');
        div.setAttribute ( 'a', 'world'); // custom properties may support
        console.log(div.title);
        console.log(div.a);//undefined
    </script>
</body>

 

</html>

Guess you like

Origin www.cnblogs.com/1998Archer/p/12586826.html