I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.
<div id="panel">
<div id="field_name">TEXT GOES HERE</div>
</div>
Here's what the function will look like:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById('field_name');
//Make replacement here
}
You can simply use:
fieldNameElement.innerHTML = "My new text!";
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.
To replace text inside a div element, use Node.textContent, which is provided in all current browsers.
fieldNameElement.textContent = "New text";
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:
It only uses the DOM, so the technique is portable to other languages, and doesn't rely on the non-standard innerHTML
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.
I would use Prototype's update method which supports plain text, an HTML snippet or any JavaScript object that defines a toString method.
$("field_name").update("New text");
Element.update documentation
$('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.
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
in IE:-
document.getElementById("field_name").innerText = newText;
in FF:-
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.
If you really want us to just continue where you left off, you could do:
if (fieldNameElement)
fieldNameElement.innerHTML = 'some HTML';
nodeValue is also a standard DOM property you can use:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
if(fieldNameElement.firstChild)
fieldNameElement.firstChild.nodeValue = "New Text";
}
el.innerHTML='';
el.appendChild(document.createTextNode("yo"));
If you're inclined to start using a lot of JavaScript on your site, jQuery makes playing with the DOM extremely simple.
http://docs.jquery.com/Manipulation
Makes it as simple as:
$("#field-name").text("Some new text.");
Use innerText if you can't assume structure
- Use Text#data to update existing text
Performance Test
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
fieldNameElement.removeChild(fieldNameElement.firstChild);
var newText = document.createTextNode("New Text");
fieldNameElement.appendChild(newText);
}
Here's an easy jQuery way:
var el = $('#yourid .yourclass');
el.html(el.html().replace(/Old Text/ig, "New Text"));
In HTML put this
<div id="field_name">TEXT GOES HERE</div>
In Javascript put this
var fieldNameElement = document.getElementById('field_name');
if (fieldNameElement)
{fieldNameElement.innerHTML = 'some HTML';}
Related
I'm making a simple step-by-step wizard for my website which asked viewers questions about their custom order. I've been using JavaScript to replace the content of each "page" with the document.getElementById('element-id').innerHTML command; however, it seems really slow and awkward to add entire divs as a string. For example, some of the code looks something like this:
function loadNextStep() {
document.getElementById('content').innerHTML = 'This is some content.<br>It seems like I need to write everything in one line to make the command work properly.<br><input type="date" id="date-picker" value=""></input>'
}
I'd love to be able to write some multi-line html code, and say "replace everything with this new html."
Is there a faster way of doing the same thing?
Thank you again!
I don't think getElementById or querySelector will make any difference, since the heavier stuff is done when you add a bunch of html elements as a string despite the fact that innerHTML can be vulnerable to cross site scripting if the output of that string has user input commands in it.
But if you still want to do this way you can do by using `` backticks to add as many lines as you'd like.
However, the way I would do is to create those elements on a different function and then output them to your loadNextStep function, then adding to your #content element using the appendChild method.
Here's a quick example of I would do:
function loadNextStep() {
var content = document.getElementById('content');
var step = step1();
step.forEach( stepContent => {
content.appendChild( stepContent );
})
}
function step1() {
var someContent = document.createElement('span');
someContent.innerText = `This is some content. It seems like I need to write everything in one line to make the command work properly.
Yes, but if you use backticks you can have multiple lines.`;
var input = document.createElement('input');
input.type = 'date';
input.id = 'date-picker';
return [ someContent, input ]
}
loadNextStep();
<div id="content">
</div>
I want to use jquery to convert text containing strings like
, etc into a more human-readable form. This works in jsfiddle:
<input id="stupid-approach" type="hidden">
function js_text(theVal) {
$("#stupid-approach").html(theVal);
x = $("#stupid-approach").html();
return x;
}
alert(js_text("é"));
But I'm wondering if there is a way to do it that does not rely on a hidden field in the DOM?
just create an empty element, there's no need to have an actual hidden element in the DOM :
function js_text(theVal) {
return $("<div />", {html: theVal}).text();
}
FIDDLE
in consideration of the feedback about jQuery's .html() method's evaluation of script tags, here is a safer native version that's not tooo unwieldy:
function js_text(theVal) {
var div=document.createElement("div");
div.innerHTML=theVal;
return div.textContent;
}
use it instead of $(xxx).html() when you don't trust the input 100%
No. There's no purely programmatic way to do this that doesn't involve getting the browser to treat the string as HTML, as in your example. (Beware untrusted inputs when doing that, by the way - it's an injection attack waiting to happen.)
You should be able to just do:
return $('<div>'+ theVal + '</div>').html();
What is the Dojo equivalent to $("...").text("asdf") and $("...").text()?
Also is there a wiki or site that provides dojo equivalents of jQuery functions?
A similar function in dojo is NodeList.text()
http://dojotoolkit.org/reference-guide/1.7/dojo/NodeList-manipulate.html#text
You can use like below.
dojo.query("#id").text("asdf");
var txt = dojo.query("#id").text();
You are looking for the dojo/dom-prop module. If you look at the source, there is special handling for the textContent property if the current browser does not support it.
if(propName == "textContent" && !has("dom-textContent")) {
ctr.empty(node);
node.appendChild(node.ownerDocument.createTextNode(value));
return node;
}
Your code would look like the following:
domProp.set(node, "textContent", "hello world!");
or
domProp.get(node, "textContent");
Just append a node to the element:
someElement.appendChild(document.createTextNode('asdf'));
You also might need to clear it beforehand:
while(someElement.firstChild) someElement.removeChild(someElement.firstChild);
As for getting the text, I don't know if there's a direct equivalent but you probably won't need one. Just read the nodeValue of the element's firstChild.
Use can do this as
dojo.query('#yourdiv')[0].lastChild.textContent = 'text';
var text = dojo.query('#yourdiv')[0].lastChild.textContent
If i had a string:
hey user, what are you doing?
How, with regex could I say: look for user, but not inside of < or > characters? So the match would grab the user between the <a></a> but not the one inside of the href
I'd like this to work for any tag, so it wont matter what tags.
== Update ==
Why i can't use .text() or innerText is because this is being used to highlight results much like the native cmd/ctrl+f functionality in browsers and I dont want to lose formatting. For example, if i search for strong here:
Some <strong>strong</strong> text.
If i use .text() itll return "Some strong text" and then I'll wrap strong with a <span> which has a class for styling, but now when I go back and try to insert this into the DOM it'll be missing the <strong> tags.
If you plan to replace the HTML using html() again then you will loose all event handlers that might be bound to inner elements and their data (as I said in my comment).
Whenever you set the content of an element as HTML string, you are creating new elements.
It might be better to recursively apply this function to every text node only. Something like:
$.fn.highlight = function(word) {
var pattern = new RegExp(word, 'g'),
repl = '<span class="high">' + word + '</span>';
this.each(function() {
$(this).contents().each(function() {
if(this.nodeType === 3 && pattern.test(this.nodeValue)) {
$(this).replaceWith(this.nodeValue.replace(pattern, repl));
}
else if(!$(this).hasClass('high')) {
$(this).highlight(word);
}
});
});
return this;
};
DEMO
It could very well be that this is not very efficient though.
To emulate Ctrl-F (which I assume is what you're doing), you can use window.find for Firefox, Chrome, and Safari and TextRange.findText for IE.
You should use a feature detect to choose which method you use:
function highlightText(str) {
if (window.find)
window.find(str);
else if (window.TextRange && window.TextRange.prototype.findText) {
var bodyRange = document.body.createTextRange();
bodyRange.findText(str);
bodyRange.select();
}
}
Then, after you the text is selected, you can style the selection with CSS using the ::selection selector.
Edit: To search within a certain DOM object, you could use a roundabout method: use window.find and see whether the selection is in a certain element. (Perhaps say s = window.getSelection().anchorNode and compare s.parentNode == obj, s.parentNode.parentNode == obj, etc.). If it's not in the correct element, repeat the process. IE is a lot easier: instead of document.body.createTextRange(), you can use obj.createTextRange().
$("body > *").each(function (index, element) {
var parts = $(element).text().split("needle");
if (parts.length > 1)
$(element).html(parts.join('<span class="highlight">needle</span>'));
});
jsbin demo
at this point it's evolving to be more and more like Felix's, so I think he's got the winner
original:
If you're doing this in javascript, you already have a handy parsed version of the web page in the DOM.
// gives "user"
alert(document.getElementById('user').innerHTML);
or with jQuery you can do lots of nice shortcuts:
alert($('#user').html()); // same as above
$("a").each(function (index, element) {
alert(element.innerHTML); // shows label text of every link in page
});
I like regexes, but because tags can be nested, you will have to use a parser. I recommend http://simplehtmldom.sourceforge.net/ it is really powerful and easy to use. If you have wellformed xhtml you can also use SimpleXML from php.
edit: Didn't see the javascript tag.
Try this:
/[(<.+>)(^<)]*user[(^>)(<.*>)]/
It means:
Before the keyword, you can have as many <...> or non-<.
Samewise after it.
EDIT:
The correct one would be:
/((<.+>)|(^<))*user((^>)|(<.*>))*/
Here is what works, I tried it on your JS Bin:
var s = 'hey user, what are you doing?';
s = s.replace(/(<[^>]*)user([^<]>)/g,'$1NEVER_WRITE_THAT_ANYWHERE_ELSE$2');
s = s.replace(/user/g,'Mr Smith');
s = s.replace(/NEVER_WRITE_THAT_ANYWHERE_ELSE/g,'user');
document.body.innerHTML = s;
It may be a tiny little bit complicated, but it works!
Explanation:
You replace "user" that is in the tag (which is easy to find) with a random string of your choice that you must never use again... ever. A good use would be to replace it with its hashcode (md5, sha-1, ...)
Replace every remaining occurence of "user" with the text you want.
Replace back your unique string with "user".
this code will strip all tags from sting
var s = 'hey user, what are you doing?';
s = s.replace(/<[^<>]+>/g,'');
Is this the correct format?
var title = new_element.setAttribute('jcarouselindex', "'items+1'");
alert(title);
No need to put the second parameter in quotes.
var title = new_element.setAttribute('jcarouselindex', items+1);
If you want to set a custom attribute then you can use HTML5 data-attributes, something like
var title = new_element.setAttribute('data-jcarouselindex', items+1);
It is syntactically correct JS/DOM, but there is no 'jcarouselindex' attribute in HTML and using setAttribute (as opposed to setting properties that map to attributes) is generally bad practice as it is buggy in MSIE (although not in such a way that will cause a problem in this case).
You might not be intending to have <foo jcarouselindex="'items+1'"> as your end result though.
Using jQuery?
var title = $('#new_element').attr('jcarouselindex', "'items+1'");
alert(title);
You have too many quotes:
var index = items + 1;
new_element.setAttribute('jcarouselindex', index);
Remark: there's no jcarouselindex attribute defined in HTML elements so this is not very clean code.