Change textNode value - javascript

Is there any way to change the value of a DOM textNode in web browser?
I specifically want to see if I can change the existing node, rather than creating a new one.
To clarify, I need to do this with Javascript. All text in the browser is stored in #textNodes which are children of other HTML nodes, but cannot have child nodes of their own.
As answered below, content can be changed by setting the nodeValue property of these Objects.

If you have a specific node (of type #text) and want to change its value you can use the nodeValue property:
node.nodeValue="new value";
Note:
innerText (and possibly textContent) will return/set both the current node and all descendent nodes text, and so may not be the behaviour you want/expect.

I believe innerHTML is used for this... Then again, that isn't W3C approved... but it works...
node.innerHTML="new value";

Related

Changes to a parent element's textContent causes the child to delete

I have a 'click' event on an image in javascript that I want to use to change the text content of the parent element when clicked. However, when I click it, the parent's text changes, but the image deletes itself. I assume I can just create and append a new child element after, but this doesn't seem to be the most efficient, and I would also like to understand why the child element gets deleted. My code looks like the following:
<body>
<ul>
<li> Hello <img src="img/hello.png"></li>
<ul>
<body>
<script>
const helloImage = document.querySelector('img')
helloImage.addEventListener('click', (e) => {
let parentEle = e.target.parentElement
parentEle.textContent = 'bye'
})
<script>
I have looked for a while for an answer, but can't seem to find anything with regards to modern javascript. I found one answer to a similar question with jQuery, but I got the same result when applying the solution's logic. Any help or if you can just point me in the right direction, I would really appreciate it. Thank you!
When you set textContent you overwrite all other child nodes.
From MDN:
Warning: Setting textContent on a node removes all of the node's children and replaces them with a single text node with the given string value.
The corresponding spec for the textContent setter says
String replace all with the given value within this.
If you only want to change the text then alter your HTML and wrap the text you want to change in a distinct element. Then reference that element's textContent in the click handler.

Why don't select and textarea value changes get updated upon cloning as with input elements?

In Firefox at least, when using cloneNode(true) on a dynamically or user-altered textarea or select element, the value property is not preserved (nor is the DOM altered to reflect dynamic changes), whereas with input elements, a change to the value property or by the user gets reflected in the DOM (so it is preserved upon the call to cloneNode). Why is there this distinction?
UPDATE:
I meant to ask: Is this behavior prescribed in a spec somewhere? (or detailed in a bug report?)
A sample is at: http://jsfiddle.net/9RSNt/1/
I suspect the difference arises because textarea and selects' values are determined by their node content. Modifying the control's value modifies their DOM properties, but not their node content, so when you clone them, the clone has the value of the original element.
You can get around this by updating their node content on the change event:
// textarea
$("textarea").change(function() { $(this).text($(this).val()); });
// select
$("select").change(function() {
var sel = $(this).children(":selected");
$(this.children).not(sel).removeAttr("selected");
sel.attr("selected", "selected");
});
http://jsfiddle.net/emr2w/8/
EDIT:
There are a number of Mozilla bug cases on this (some resolved and some not), but any mention of the actual specs are few and far between. It seems that the the behavior of the value property after a cloneNode() may be a gray area that is not clearly defined in the spec. After all, the purpose of cloneNode() is to clone a DOM node, and not necessarily its object state.
https://bugzilla.mozilla.org/show_bug.cgi?id=197294
https://bugzilla.mozilla.org/show_bug.cgi?id=230307
https://bugzilla.mozilla.org/show_bug.cgi?id=237783

Accessing the value of an "em" tag in javascript

How would you access the value of an em tag in javascript?
This is the element I'm trying to access: <em id='tag_IS_System_Agent'></em>
which displays: John Smith
I'm trying to access it via javascript:
document.getElementById("emailFrame").src
= "http://www.website.org/mail.php?cid="
+IS_ATTR_ID.value
+"&name="+document.write("<em id=\"tag_IS_System_Agent\"> <\/em>")
+"&em="+email;`
Any idea? I know that document.write("<em id=\"tag_IS_System_Agent\"> <\/em>") is wrong and I'm stumped and not sure what to do.
Accessing the value based on your markup would be:
var myValue = document.getElementById("tag_IS_System_Agent").textContent
By “the value of an ‘em’ tag”, you apparently mean the content of an em element. If the element has an id attribute, as in your example, you can use the getElementById method of document to access the element node in the DOM. Then you can get the content of the element, serialized as HTML, using the innerHTML property. Note that this will include markup for inner elements, if any. So the expression you would use would be
document.getElementById('tag_IS_System_Agent').innerHTML
Instead of innerHTML, you could use textContent, which gives you just the textual content, without any inner tags. However, this is less widely supported (e.g., not in IE 8). If there is no inner markup, the results are the same, but innerHTML is thus safer.

What is the difference between appendChild, insertAdjacentHTML, and innerHTML

I want to know what the difference is between appendChild, insertAdjacentHTML, and innerHTML.
I think their functionality are similar but I want to understand clearly in term of usage and not the execution speed.
For example, I can use innerHTML to insert a new tag or text into another tag in HTML but it replaces the current content in that tag instead of appends.
If I would like to do it that way (not replace) I need to use insertAdjacentHTML and I can manage where I want to insert a new element (beforebegin, afterbegin, beforeend, afterend)
And the last if I want to create (not insertion in current tag) a new tag and insert it into HTML I need to use appendChild.
Am I understanding it correctly? Or are there any difference between those three?
element.innerHTML
From MDN:
innerHTML sets or gets the HTML syntax describing the element's descendants.
when writing to innerHTML, it will overwrite the content of the source element. That means the HTML has to be loaded and re-parsed. This is not very efficient especially when using inside loops.
node.appendChild
From MDN:
Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.
This method is supported by all browsers and is a much cleaner way of inserting nodes, text, data, etc. into the DOM.
element.insertAdjacentHTML
From MDN:
parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. [ ... ]
This method is also supported by all browsers.
....
The appendChild methods adds an element to the DOM.
The innerHTML property and insertAdjacentHTML method takes a string instead of an element, so they have to parse the string and create elements from it, before they can be put into the DOM.
The innerHTML property can be used both for getting and setting the HTML code for the content of an element.
#Guffa did explain the main difference ie innerHTML and insertAdjacentHTML need to parse the string before adding to DOM.
In addition see this jsPerf that will tell you that generally appendChild is faster for the job it provides.
One that I know innerHTML can grab 'inner html', appendChild and insertAdjacentHTML can't;
example:
<div id="example"><p>this is paragraph</p><div>
js:
var foo = document.getElementById('example').innerHTML;
end then now
foo = '<p>this is paragraph</p>';
DOCS:
appendChild
insertAdjacentHTML
innerHtml
innerHTML vs appendChild() performance
insertAdjacentHTML vs innerHTML vs appendChild performance
the main difference is location (positioning) :
(elVar mean element saved to variable)
** elVar.innerHTML: used to sets/get text and tags (like ) inside an element (if u use "=" it replace the content and "+=" will add to the end.
** divElvar.appendChild(imgElVar): to add pure element to the end of another element (or start with prepend) .
** insertedElVar.insertAdjacentElement(beforebegin,targetElvar): it insert element into spicific location before elVar (after it with "afterend").
-innerText: can replace/get/insertOnEnd text.but can read tags and text inside element with display:hidden , cant insert on start .
-innercontent : show all text inc hidden , cant read html tags and it put empty spaces instead of them , cant insert on start
-innerHTML: read all set all , cant insert on start
-prepend : insert text at start of elvar (but cant use to get/replace text or html)
prepend was needed for start, after it made its easy to make append , not for a need , its just bcz lol

pure javascript dom dynamic insert, update and delete

I want to know the most effctive way to dynamically update, insert or remove elements from an html page.
The outcome of this is that, I can change an input element into a div element and vice versa based on a user action.
eg
<form><input type="text" value="Value to save"/></form>
and based on some event, i will change that to
<form><div>Value to Save</div></form>
Tx
I think you could do this task this way (pure JS, without using external frameworks):
//retrieve the <form>
var form = document.getElementsByTagName('form')[0];
//retrieve the <input> inside the form
var input = form.getElementsByTagName('input')[0];
//create a new <div> DOM element
var newElement = document.createElement('div');
//The containing div text is equal to the input value (your case)
newElement.innerHTML = input.value;
//simple empty the form by set innerHTML = ""
form.innerHTML = "";
//append the <div> inside the form
form.appendChild(newElement);
By the way, I sugges you, if you want to manipulate DOM and do stuff like these in an easier way, learn how to do it by using frameworks like jQuery or mootools ;)
This is a general description:
Creating: You can create elements with document.createElement and then use one the various insertion methods to the insert the element at a certain position (e.g. Node.appendChild). You need to get references to related nodes first.
Most browser also support the innerHTML attribute for elements. You can set that attribute to an HTML(or text) string and the content of the element will be updated accordingly.
Updating: It depends on which data you want to update. E.g. an input element has an attribute value. In order to change the value of a text input you need to get a reference to that element first, then you can do element.value = 'new value'. For content, you can use the already mentioned innerHTML attribute.
Have a look at an HTML element reference to see what attributes they have.
Deleting: You want Node.removeChild.
I suggest to also have a look at DOM traversal methods and be aware of browser differences.
Using:
element.removeChild
element.appendChild
By using these methods, you can retain references to the elements in case you want to swap them back over again. Any event handlers in place will remain attached to the elements, too.
This depends on your definition of most effective.
If you mean the simplest way, then you can use a library like jQuery and do it like this:
$('form').html('<dynamic markup>');
If you mean the most performant way you can do the following:
document.getElementByTagName('form').innerHTML = '<dynamic markup>';

Categories