Javascript change data in div

How do I replace text inside a div element?

I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.

function showPanel(fieldName) < var fieldNameElement = document.getElementById('field_name'); //Make replacement here >

Does the accepted answer do what you want it to when assigned text like is:- This is big. If this behaviour is desirable then can you re-phrase the question to match?

14 Answers 14

fieldNameElement.innerHTML = "My new text!"; 

element.innerHTML = ««; won’t be a good idea. element.innerHTML = «& neither will this»;

Updated for everyone reading this in 2013 and later:

This answer has a lot of SEO, but all the answers are severely out of date and depend on libraries to do things that all current browsers do out of the box.

fieldNameElement.textContent = "New text"; 

You might consider elaborating on why textContent is a superior method to innerHTML : it’s faster, safer, and more appropriate when not deliberately trying to insert HTML markup.

 function showPanel(fieldName) < var fieldNameElement = document.getElementById("field_name"); while(fieldNameElement.childNodes.length >= 1) < fieldNameElement.removeChild(fieldNameElement.firstChild); >fieldNameElement.appendChild(fieldNameElement.ownerDocument.createTextNode(fieldName)); > 

The advantages of doing it this way:

  1. It only uses the DOM, so the technique is portable to other languages, and doesn’t rely on the non-standard innerHTML
  2. fieldName might contain HTML, which could be an attempted XSS attack. If we know it’s just text, we should be creating a text node, instead of having the browser parse it for HTML

If I were going to use a javascript library, I’d use jQuery, and do this:

 $("div#field_name").text(fieldName); 

Note that @AnthonyWJones’ comment is correct: «field_name» isn’t a particularly descriptive id or variable name.

This is good answer, better than mine and is the correct answer. You might consider tidying the example though. ‘fieldname’ is not a good name for the function’s parameter. In fact it might be best to take two one for the element ID and another for the content, i.e.; elemID, content

The question probably used field_name to make the example generic. Also the questioner mentions that Prototype is available but not jQuery.

I would use Prototype’s update method which supports plain text, an HTML snippet or any JavaScript object that defines a toString method.

@Aeyoun The OP implied they were already using Prototype, so if that’s the case it makes sense to take advantage of it.

$('field_name').innerHTML = 'Your text.'; 

One of the nifty features of Prototype is that $(‘field_name’) does the same thing as document.getElementById(‘field_name’) . Use it! 🙂

John Topley’s answer using Prototype’s update function is another good solution.

Don’t use innerHTML. It’s not a w3c recommendation and behaves inconsistently. It’s considered bad style.

Milan, the more accepted way is to loop through the childNodes, call removeNode(true) on each, then append new nodes created using document.createElement() or document.createTextNode(). If you need to do that I would recommend writing a function to avoid a lot of typing.

@RaduSimionescu No, it isn’t. This question and answer is about Prototype.js, not jQuery. In Prototype $ looks up an item by ID. It’s not selector-based like jQuery is. api.prototypejs.org/dom/dollar

The quick answer is to use innerHTML (or prototype’s update method which pretty much the same thing). The problem with innerHTML is you need to escape the content being assigned. Depending on your targets you will need to do that with other code OR

document.getElementById("field_name").innerText = newText; 
document.getElementById("field_name").textContent = newText; 

(Actually of FF have the following present in by code)

HTMLElement.prototype.__defineGetter__("innerText", function () < return this.textContent; >) HTMLElement.prototype.__defineSetter__("innerText", function (inputText) < this.textContent = inputText; >) 

Now I can just use innerText if you need widest possible browser support then this is not a complete solution but neither is using innerHTML in the raw.

Источник

javascript replace content in div [closed]

It’s difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.

I have an ajax script working that fills a div on a page with search results returned from the server. Each search result has a hyper link with second javascript function that sets hidden input value on the page for posting back to the server, depending on which result is clicked on by user. All of that is working fine. However, in the second javascript function I also want to set the contents of the original div to the selected value and I cannot get this to work. html on starting page

function setResult(varname) < document.getElementById('chosenresult').value = varname; //WORKS FINE document.getElementById('results').value = varname; //DOES NOT WORK document.getElementById('results').innerHTML = varname; //ALTERNATIVE ALSO DOES NOT WORK return false; >

In other words, I can set the value in the hidden input field, but cannot replace the contents of the «results» div. Thanks for any suggestions! EDIT: I FOUND THE MISTAKE. Putting a div in the value for the hidden input tab worked as a hack to set the value but was unecessary and seems to have broken the code so the results div was not set. In lieu of a div, simply giving an id to the hidden input tab and setting its value in javascript works as follows: html

document.getElementById('chosenresult').value = varname; //WORKS FINE document.getElementById('results').innerHTML = varname; //NOW WORKS 

Источник

How can I change div content with JavaScript?

I just wanted to be able to change the div’s content (it’s inner html) with selecting one of «A» or «B» radio buttons, but div#content does not have javascript attribute «value», so I am asking how it can be done.

6 Answers 6

Assuming you’re not using jQuery or some other library that makes this sort of thing easier for you, you can just use the element’s innerHTML property.

document.getElementById("content").innerHTML = "whatever"; 

On a side note, document.getElementById(«content»).innerText = «bold text?«; will behave differently, and sometimes quite usefully, to document.getElementById(«content»).innerHTML = «bold text?«;

Please use innerHTML rather than innerText and textContent because innerHTML is compatible to all browsers.

Warning! the usage of innerHTML can easily lead to XSS vulnerabilities when the value comes from an untrusted input. The use of innerText is always recommended for security reasons and currently it is supported by all browsers (caniuse.com/#feat=innertext)

can I assign an other div element through innerHTML, something like document.getElementById(«foo»).innerHTML =

.

Get the id of the div whose content you want to change then assign the text as below:

 var myDiv = document.getElementById("divId"); myDiv.innerHTML = "Content To Show"; 

Welcome to Stackoverflow! Providing a little bit of explanation when you write code in your answer is far more helpful than just the code.

you can use following helper function:

function content(divSelector, value) < document.querySelector(divSelector).innerHTML = value; >content('#content',"whatever"); 

Where #content must be valid CSS selector

Additionaly — today (2018.07.01) I made speed comparison for jquery and pure js solutions ( MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):

document.getElementById("content").innerHTML = "whatever"; // pure JS $('#content').html('whatever'); // jQuery 

enter image description here

The jquery solution was slower than pure js solution: 69% on firefox, 61% on safari, 56% on chrome. The fastest browser for pure js was firefox with 560M operations per second, the second was safari 426M, and slowest was chrome 122M.

So the winners are pure js and firefox (3x faster than chrome!)

Источник

Читайте также:  Python type file pdf
Оцените статью