Setelah mempelajari bahasa markup seperti XML dan HTML, kita seharusnya sudah mengetahui apa yang disebut dengan tag dan attribut. Dalam HTML maupun XML, atribut adalah bagian dari tag yang mempunyai nilai,
walaupun ada juga atribut yang bisa ditulis tanpa nilai. Untuk mendapatkan nilai tersebut, dalam javascript kita bisa menggunakan properti-properti yang mewakili masing-masing atribut HTML karena atribut dalam HTML memang terbatas dan punya kegunaan khusus. Tapi, untuk XML, kita tidak bisa mendapatkan nilai atribut lewat properti karena atribut dalam XML namanya bebas dan tidak punya kegunaan khusus selain untuk menyimpan nilai berupa string. Untuk mendapatkan nilai dari atribut dalam
XML, kita bisa menggunakan method getAttribute(). Selain digunakan dalam XML, getAttribute juga bisa digunakan untuk mendapatkan nilai atribut tag HTML. Mungkin untuk lebih jelasnya saya perlu langsung memberikan contoh script yang sudah diletakkan dalam kode HTML. Pada contoh di atas, saya sudah mencontohkan penggunaan getAttribute() yang ada di dalam elemen HTML maupun XML. Cara penggunaan getAttribute() untuk HTML dan XML hampir sama. Kita perlu mendapatkan objek yang mewakili elemen yang ingin kita ambil atributnya dengan getElemensByTagNama(), GetElemenById(), dll. Setelah objek didapatkan, kita cukup menggunakan method getAttribute pada objek yang kita inginkan.
The Parameters
The namespace in which to look for the specified attribute. name The name of the attribute to look for. Return value The string value of the specified attribute. If the attribute doesn't exist, the result is Note: Earlier versions of the DOM specification had this method described as returning an empty string for non-existent attributes, but it was not typically implemented this way since null makes more sense. The DOM4 specification now says this method should return null for non-existent attributes. Examples The following SVG document reads the value of the
In an HTML document the attribute has to be
accessed with
Notes Namespaces are only supported in XML documents. HTML documents have to use Prior to the DOM4 specification, this method was specified to return an empty string rather than null for non-existent attributes. However, most
browsers instead returned null. Starting with DOM4, the specification now says to return null. However, some older browsers return an empty string. For that reason, you should use DOM methods dealing with element's attributes: Specifications
Browser compatibilityBCD tables only load in the browser See also |