如何用JavaScript编写document.getElementById()方法的缩写

如何用JavaScript编写document.getElementById()方法的缩写

任务是使用JavaScript编写document.getElementById()的缩写来选择具有指定id的元素。我们将讨论几种技术。

方法1

  • 定义一个函数返回 document.getElementById(‘idName’)
  • 该方法以 IDName 作为唯一参数。
  • ID 作为参数调用该方法。

示例: 在这个示例中,创建了一个返回 document.getElementById(‘idName’) 的函数。

<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        Write Shorthand for document.getElementById() 
        method in JavaScript
    </title>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <p>
        Click on the button to select the 
        element by shorthand instead of 
        getElementById
    </p>
 
    <button onclick="GFG_Fun()">
        click here
    </button>
 
    <p id="result"></p>
 
    <script>
        let ID = function (elementId) {
            return document.getElementById(elementId);
        };
 
        let res = ID("result");
 
        function GFG_Fun() {
            res.innerHTML = "Element selected by "
                + "shorthand of getElementById";
        }
    </script>
</body>
 
</html>

输出:

如何用JavaScript编写document.getElementById()方法的缩写

方法2

  • 定义一个原型 = document.getElementById
  • 通过将 IDName 作为 document.getElementById 的替代参数,在需要的地方使用这个原型。

示例: 在这个示例中,创建了一个HTMLDocument原型,然后使用它来选择元素,传入 IDName

<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        Write Shorthand for document.getElementById()
        method in JavaScript
    </title>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <p>
        Click on the button to select the
        element by shorthand instead of
        getElementById
    </p>
 
    <button onclick="GFG_Fun()">
        click here
    </button>
 
    <p id="result"></p>
 
    <script>
        HTMLDocument.prototype.e = document.getElementById;
 
        let res = document.e("result");
 
        function GFG_Fun() {
            res.innerHTML = "Element selected by "
                + "shorthand of getElementById";
        }
    </script>
</body>
 
</html>

输出:

如何用JavaScript编写document.getElementById()方法的缩写

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程