Writing HTML to a webpage using document.getElementById('results').childNodes[0].nodeValue

D

Deryck

Hi,

I am trying to update part of a webpage using javascript. The bit that gets
updated will have a variable number of links written to it.

I have done this successfully by rewriting the whole page but this seems
like overkill (and a maintenance problem too potentially).

I thought about defining the area to be updated using a div. Something like
this:

<div id="results">Results will go here</div>

with the javascript doing something like:

var src = "blah blah blah";
document.getElementById('results').childNodes[0].nodeValue = src;

This works if src is just text. If it is HTML, say:

var src="<p><a href=\"some_file.html\">Some file</a></p>";

Then inside the div instead of getting a link to some_file.html I get the
raw HTML.

Is there either a way round this problem or a much better way of doing it in
the first place?

Thanks

Deryck
 
M

Martin Honnen

Deryck wrote:

I thought about defining the area to be updated using a div. Something like
this:

<div id="results">Results will go here</div>

with the javascript doing something like:

var src = "blah blah blah";
document.getElementById('results').childNodes[0].nodeValue = src;

This works if src is just text. If it is HTML, say:

var src="<p><a href=\"some_file.html\">Some file</a></p>";

Then inside the div instead of getting a link to some_file.html I get the
raw HTML.

Is there either a way round this problem or a much better way of doing it in
the first place?

Learn the DOM e.g.
var p = document.createElement('p');
var link = document.createElement('a');
a.href = 'some_file.html';
p.appendChild(a);

var resultsDiv = document.getElementById('results');
while (resultsDiv.hasChildNodes()) {
resultsDiv.removeChild(resultsDiv.lastChild);
}

resultsDiv.appendChild(p);

or help yourself with innerHTML

resultsDiv.innerHTML = '<p><a ...>...<\/a><\/p>';
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top