Why can't I set value to display in a div? - javascript

So I'm new to JavaScript and I'm trying to figure out why doesn't this work:
My function has this line:
document.getElementById("displayResult").value = ("test");
and this is my div:
<div id="displayResult"></div>

div's don't have a value property. You want to set the .innerText property.
And by all means, have fun testing things yourself, but you'll find it a lot easier if you use a framework to do these things (like jQuery)

You will want to use - .innerHTML no?
document.getElementById("displayResult").innerHTML = "<b>test</b>";

.value is only a valid attribute on form fields. You likely want to use the following code:
document.getElementById("displayResult").innerHTML = "test";

you have to test if innerHTML is supported by your brwser. As it is not the DOM Standard.
You can write it like
var oDiv = document.getElementById("displayResult")
if(typeof oDiv.innerHTML != undefined) {
oDiv .innerHTML = message;
} else {
oDiv .appendChild(document.createTextNode(message));
}

Related

How to fill this textbox? [duplicate]

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';}

Cross-browser innerText for setting values

Let's say I have the following code:
<html>
<head></head>
<body>
<div id="d">some text</div>
<script type="text/javascript">
var d = document.getElementByid('d');
var innerText = d.innerText || d.textContent;
innerText = 'new text';
</script>
</body>
</html>
And I want to change text value for the div tag with id='d'. Unfortunately the block code above doesn't work and the text content doesn't change.
It works if do the following recipe:
if (d.innerText) d.innerText = 'new text';
else d.textContent = 'new text';
But I dont like the recipe above because it's not compact.
Have you any suggestions why the first approach doesn't work?
Instead of multiple assignments, you can grab the property and use that
var text = ('innerText' in d)? 'innerText' : 'textContent';
d[text] = 'New text';
The first approach doesn't work because all it does is set the variable to the new value, it doesn't write the value to the element. The line
var innerText = d.innerText || d.textContent;
...sets the variable innerText to the value of the text property it finds, it's not a reference to the actual property itself.
You'll have to do the branch, e.g.:
var d = document.getElementById('d');
var msg = "new text";
if ("innerText" in d) {
d.innerText = msg;
}
else {
d.textContent = msg;
}
That feature-detects whether the browser uses innerText or textContent by looking for the existence of the property on the element (that's what the in operator does, check if an object has a property with the given name, even if that property is blank, null, undefined, etc.).
You can even write yourself a function for it:
var setText = (function() {
function setTextInnerText(element, msg) {
element.innerText = msg;
}
function setTextTextContent(element, msg) {
element.textContent = msg;
}
return "innerText" in document.createElement('span') ? setTextInnerText : setTextTextContent;
})();
That does the feature-detection once, and returns a function any half-decent engine will inline for you.
Or alternately, if you want HTML markup in the message to be handled as markup (rather than literal text), you can just use innerHTML (which is consistent across browsers). But again, if you use innerHTML, markup will be processed which may not be what you want.
I find it useful to use a good JavaScript library to deal with these browser differences (and to provide a ton of useful further functionality), such as jQuery, YUI, Closure, or any of several others. Obviously there's nothing you can do with a library you can't do without one, it's just a matter of standing on the shoulders of people who've done a huge amount of work already. :-)
In this case, for instance, using jQuery the above would be:
$("#d").text("new text");
That's it.
d.appendChild(document.createTextNode("new text");
you can use textContent only & it will work in major browsers... (FF, Safari & Chrome)
var d = document.getElementById('d');
var msg = "new text";
d.textContent = msg;

Dojo equivalent to jQuery.text function?

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

javascript getElementById and convert it to String

is there a way to convert a javascript HTML object to a string?
i.e.
var someElement = document.getElementById("id");
var someElementToString = someElement.toString();
thanks a lot in advance
If you want a string representation of the entire tag then you can use outerHTML for browsers that support it:
var someElementToString = someElement.outerHTML;
For other browsers, apparently you can use XMLSerializer:
var someElement = document.getElementById("id");
var someElementToString;
if (someElement.outerHTML)
someElementToString = someElement.outerHTML;
else if (XMLSerializer)
someElementToString = new XMLSerializer().serializeToString(someElement);
You can always wrap a clone of an element in an 'offscreen', empty container.
The container's innerHTML is the 'outerHTML' of the clone- and the original.
Pass true as a second parameter to get the element's descendents as well.
document.getHTML=function(who,deep){
if(!who || !who.tagName) return '';
var txt, el= document.createElement("div");
el.appendChild(who.cloneNode(deep));
txt= el.innerHTML;
el= null;
return txt;
}
someElement.innerHTML
As Darin Dimitrov said you can use element.innerHTML to display the HTML element childnodes HTML. If you are under IE you can use the outerHTML propoerty that is the element plus its descendants nodes HTML
You just have to create one variable then store value into it. As in one my project I have done the same thing and it works perfectly.
var message = "";
message = document.getElementById('messageId').value;
test it.. It will definitely work.

how to remove css property using javascript?

is it possible to remove a CSS property of an element using JavaScript ?
e.g. I have div.style.zoom = 1.2,
now i want to remove the zoom property through JavaScript ?
You have two options:
OPTION 1:
You can use removeProperty method. It will remove a style from an element.
el.style.removeProperty('zoom');
OPTION 2:
You can set it to the default value:
el.style.zoom = "";
The effective zoom will now be whatever follows from the definitions set in the stylesheets (through link and style tags). So this syntax will only modify the local style of this element.
removeProperty will remove a style from an element.
Example:
div.style.removeProperty('zoom');
MDN documentation page:
CSSStyleDeclaration.removeProperty
div.style.removeProperty('zoom');
element.style.height = null;
output:
<div style="height:100px;">
// results:
<div style="">
You can use the styleSheets object:
document.styleSheets[0].cssRules[0].style.removeProperty("zoom");
Caveat #1: You have to know the index of your stylesheet and the index of your rule.
Caveat #2: This object is implemented inconsistently by the browsers; what works in one may not work in the others.
You can try finding all elements that have this class and setting the "zoom" property to "nothing".
If you are using jQuery javascript library, you can do it with $(".the_required_class").css("zoom","")
Edit: Removed this statement as it turned out to not be true, as pointed out in a comment and other answers it has indeed been possible since 2010.
False: there is no generally known way for modifying stylesheets from JavaScript.
You can also do this in jQuery by saying $(selector).css("zoom", "")
This should do the trick - setting the inline style to normal for zoom:
$('div').attr("style", "zoom:normal;");
actually, if you already know the property, this will do it...
for example:
var txt = "";
txt = getStyle(InterTabLink);
setStyle(InterTabLink, txt.replace("zoom\:1\.2\;","");
function setStyle(element, styleText){
if(element.style.setAttribute)
element.style.setAttribute("cssText", styleText );
else
element.setAttribute("style", styleText );
}
/* getStyle function */
function getStyle(element){
var styleText = element.getAttribute('style');
if(styleText == null)
return "";
if (typeof styleText == 'string') // !IE
return styleText;
else // IE
return styleText.cssText;
}
Note that this only works for inline styles... not styles you've specified through a class or something like that...
Other note: you may have to escape some characters in that replace statement, but you get the idea.
To change all classes for an element:
document.getElementById("ElementID").className = "CssClass";
To add an additional class to an element:
document.getElementById("ElementID").className += " CssClass";
To check if a class is already applied to an element:
if ( document.getElementById("ElementID").className.match(/(?:^|\s)CssClass(?!\S)/) )

Categories