Método HTML DOM getAttribute()

En este artículo, aprenderemos sobre el método HTML DOM getAttribute() , además de comprender su implementación a través del ejemplo.

El método HTML DOM getAttribute() se utiliza para obtener el valor del atributo del elemento. Al especificar el nombre del atributo, puede obtener el valor de ese elemento. Para obtener los valores de los atributos no estándar, podemos usar el método getAttribute().

Sintaxis:

Object.getAttribute(attributename)

Valor del parámetro:

  • atributoname : Es un parámetro requerido con tipo de string que especifica el nombre del atributo que necesita recuperar el valor.

Valor devuelto: Devuelve el valor de un atributo especificado en el elemento. Devolverá un valor nulo o una string vacía si el atributo especificado no existe.

Ejemplo 1:  Este ejemplo ilustra el método DOM getAttribute() que especifica el valor del atributo para el nombre especificado de un elemento.

HTML

<!DOCTYPE html>
<html>
 
<head>
    <title>DOM getAttribute() Method</title>
</head>
 
<body>
    <center>
        <h1 style="color:green;width:50%;">
            GeeksforGeeks
        </h1>
        <h2>DOM getAttribute() Method</h2>
        <br>
        <button id="button" onclick="geeks()">Submit</button>
        <p id="gfg"></p>
 
         
        <script>
        function geeks() {
            var rk =
            document.getElementById("button").getAttribute("onClick");
            document.getElementById("gfg").innerHTML = rk;
        }
        </script>
    </center>
</body>
 
</html>

Producción:

Método DOM getAttribute()

Ejemplo 2: Este ejemplo ilustra el método DOM getAttribute() para recuperar el valor del atributo href de un elemento.

HTML

<!DOCTYPE html>
<html>
 
<head>
    <title>DOM getAttribute() Method</title>
</head>
 
<body>
    <center>
        <h1 style="color:green;width:50%;">
                GeeksforGeeks
            </h1>
        <h2>DOM getAttribute() Method</h2>
        <a id="gfg" href="www.geeksforgeeks.com">
          GeeksforGeeks
        </a>
        <br>
        <br>
        <button id="button" onclick="geeks()">Submit</button>
        <br>
        <p id="rk"></p>
 
         
        <script>
        function geeks() {
            var rk = document.getElementById("gfg").getAttribute("href");
            document.getElementById("rk").innerHTML = rk;
        }
        </script>
    </center>
</body>
 
</html>

Producción:

Método DOM getAttribute()

Navegadores compatibles: los navegadores compatibles con el método DOM getAttribute() se enumeran a continuación: 

  • Google Chrome 1.0
  • Internet Explorer 5.0
  • Microsoft Edge 12.0
  • Firefox 1.0
  • Ópera 8.0
  • Safari 1.0

Publicación traducida automáticamente

Artículo escrito por bestharadhakrishna y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *