JavaScript / setAttribute
π Today I Learned
- setAttribute()
Q. classμ id λ§κ³ λ λ€λ₯Έ attributeλ₯Ό μΆκ°ν μλ μλμ?
.setAttribute()
λ μ νν μμ(element)μ μμ±(attribute) κ°μ μ νλ€.
element.setAttribute( 'attributename', 'attributevalue' )
attributename
μλ μμ± μ΄λ¦μ, attributevalue
μλ μμ±κ°μ λ£λλ€.
μλ₯Ό λ€μ΄
document.getElementById( 'music' ).setAttribute( 'SoYoon', 'Wings' )
id κ°μ΄ 'music'μΈ μμμ 'SoYoon' μμ±μ 'Wings'λ‘ μ νλ€. λ§μ½ μ΄λ―Έ μμ±κ°μ΄ μ‘΄μ¬νλ€λ©΄ κ·Έ κ°μ μ§μ°κ³ μ κ°μ μ μ©νλ€.
id κ°μ΄ 'cat'μΈ μμμ 'href' μμ±κ°μ λ³κ²½νλ€.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>JavaScript | .setAttribute()</title>
</head>
<body>
<p><a id="cat" href="#">CUTE CAT, I LOVE U</a></p>
<script>
document.getElementById( 'cat' ).setAttribute( 'href', 'https://en.wikipedia.org/wiki/Cat' );
</script>
</body>
</html>