开发者

How to use replace in div?

I have got one question, how to use javascript replace() in div tag? I tried it like that:

<html>
<body>
<div id="ahoj">ahoj</div>

<script type="text/javascript">

document.write(document.getElementById("ahoj").replace("ahoj","hola"));

</script>
</body开发者_如何学Go>
</html>

...but it is not working.. Any ideas?


document.getElementById("ahoj") is an HTMLElement object. Use document.getElementById("ahoj").innerHTML

document.write(document.getElementById("ahoj").replace(/ahoj/g,"hola"));

Or if you don't want a new element:

document.getElementById("ahoj").innerHTML = document.getElementById("ahoj").innerHTML.replace(/ahoj/g,"hola"); 

Replace the string and set the innerHTML to the new string. Example


I think innerHTML is what you'll need to use.

document.write(document.getElementById("ahoj").innerHTML.replace("ahoj", "hola"));


<script type="text/javascript">
    var el = document.getElementById("ahoj");
    el.innerHTML = el.innerHTML.replace(/ahoj/g,”hola”);
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜