admin管理员组

文章数量:1326326

I am trying to change the contents of a div without using jQuery. I want to select the div by id or class.

Ive managed to get append to work:

function appendHtml(targetC, htmldata) {
    var theDiv = document.getElementById(targetC);
    var newNode = document.createElement('div');
    newNode.innerHTML = htmldata;
    theDiv.appendChild(newNode) 
}

But cant figure out how to change text of one..

Any ideas?

I am trying to change the contents of a div without using jQuery. I want to select the div by id or class.

Ive managed to get append to work:

function appendHtml(targetC, htmldata) {
    var theDiv = document.getElementById(targetC);
    var newNode = document.createElement('div');
    newNode.innerHTML = htmldata;
    theDiv.appendChild(newNode) 
}

But cant figure out how to change text of one..

Any ideas?

Share Improve this question asked Mar 8, 2013 at 14:44 AlosyiusAlosyius 9,15126 gold badges78 silver badges121 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 5

see this fiddle for a basic sample

<html>
<head>
<script>
    function bold(targetC) {
        var theDiv = document.getElementById(targetC);
        theDiv.innerHTML = '<b>' + theDiv.innerHTML + '</b>';
    }
</script>
</head>

<body onload='bold("message")'>
   <div>Hello, World!</div>
   <div id="message">What a nice day!</div>
</body>
</html>

Edited:

<div id="foo">old text</div>   

The JS code:

function appendHtml(targetC, htmldata) {
    var theDiv = document.getElementById(targetC);
    theDiv.innerHTML = htmldata;
}

appendHtml('foo', 'new text');

Here is a fiddle: http://jsfiddle/7QjcB/

simply change the html of a div by using innerHTML

var anyDiv = document.getElementById(targetID);

html = "content";
anydiv.innerHTML(html);

as a variation of your provided function:

function changeHtml(targetC, htmldata) {
    var theDiv = document.getElementById(targetC);
    theDIV.innerHTML = htmldata;

}

Here is a fiddle that might answer your question. All I changed was getting the element before and then passing it in.

function appendHtml(targetC, htmldata) {
var newNode = document.createElement('div');
newNode.innerHTML = htmldata;
targetC.appendChild(newNode);
}

var getDiv = document.getElementById("testing");

本文标签: javascriptChange element text without jQueryStack Overflow