2016-10-29 2 views
-1

js의 replaceChild를 사용하여 버튼을 클릭하면 id = 'water'인 스팬을 앵커로 바꿔야합니다. fff() 잘 작동하므로 문제가 있다고 생각하는 마지막 두 줄 때까지 ff() 않습니다. (replaceChild가 어떻게 작동하는지 파악할 수 없다.) 내가 Element.replaceChild 다른 요소에 의해 요소의 자식을 대체하는 데 사용되는 버튼 http://prntscr.com/d0b95vreplaceChild를 사용하여 span 태그를 anchor 태그로 바꾸기 javacript

답변

0

을 클릭하면

function fff() { 
     var ss = document.createElement('span'); 
     var text = document.createTextNode('https://www.google.com/'); 
     ss.appendChild(text); 
     document.getElementById('water').appendChild(ss); 
    } 
    function ff() { 
     var s = document.createElement('a'); 
     var t = document.createTextNode("https://www.google.com/"); 
     s.appendChild(t); 
     s.href = "http://example.com"; 
     var item = document.getElementById('water'); 
     item.replaceChild(s, item); 
    } 

<body onload="fff()"> 
<span id="water"></span> <br><br> 
<button onclick="ff()">Replace with anchor</button> 
</body> 

은 내가이 얻을. span # water를 바꾸려면 부모 (즉, <body>)를 선택하고 replaceChild를 호출해야합니다. 당신은 ff의 마지막 라인을 다음과 같이 바꿀 수도 있습니다

var body = document.body; 
body.replaceChild(s, item); 
+1

또는보다 일반적인 해결책은's.parentNode.replaceChild (...)'입니다. – CBroe

관련 문제