I need to change the text inside HTML element using javascript, but I have no idea about how to do it. ¿Any help?
I've got it defined like:
<h2 id="something">Text I want to change.</h2>
Im trying to do it with:
document.getElementById("something").value = "new text";
But it doesn't work.
Thanks
You can use innerHTML:
document.getElementById("something").innerHTML = "new text";
If the element only contains text, textContent works better and faster than innerHTML
document.getElementById("something").textContent = 'new text';
Good luck
:)
Though the following code would be the fastest alternative to slow .innerHTML:
var element = document.getElementById('something');
// removing everything inside the node
while (element.firstChild) {
element.removeChild(element.firstChild);
}
// appending new text node
element.appendChild(document.createTextNode('new text'));
And here is the benchmark:
JSPerf: http://jsperf.com/replace-text-in-node
Related
Is it possible to append a second child into the first appendchild created in a single line of code?
Something like this:
document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text)));
This works fine, but i want to know why it doesn't work the same way in a single line of code.
let p = document.createElement('p');
p.appendChild(document.createTextNode('Some Text'));
document.body.appendChild(p);
document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text')));
evaluates to
const p = document.createElement('p');
const node = document.createTextNode('Some Text');
document.body.appendChild(node);
because document.createTextNode is the last thing called, which returns the DOM node of the text
So when you run this, 'Some Text' is added to the DOM, but it's not actually inside the <p> tag
You should append the paragraph first, so this code
document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text)));
should be like this:
document.body.appendChild(document.createElement('p')).appendChild(document.createTextNode('Some Text')));
As part of a bunch of javascript a bunch of HTML is generated:
//for loop
var title = document.createElement('strong');
title.className = "titleSub";
//more add etc.
So this part is working correctly:
That text in there crom from a database call. All I'm trying to do is override this text:
$(document).ready(function() {
$(".titleSub").Text("sss");
});
However, this code is not applying and the text is not updated. What am I doing wrong and how do I fix it??
It is .text() and not .Text() and JavaScript is CaSe SeNsItIvE.
$(document).ready(function() {
$(".titleSub").text("sss");
});
When building the element title, try
title.innerText = 'sss';
Or if you wish to do after the element is inserted into the DOM
$('.titleSub').text('sss');
Try .innerText() or .innerHtml instead of .Text()
I need to extract the text that is directly under an HTML tag. For example, if my HTML looks like:
<span>This is Outside Text
<span>This is Inside Text</span>
</span>
then I need a way to extract ONLY "This is Outside Text" and NOT "This is Inside Text". I have tried "innerHTML", innerText", "textContent" and also tried to use RegEx (although I am not very good at it). But I am unable to find a solution. Any help would be much appreciated.
Please note that due to some technical constraints, I need to use "plain" Javascript ONLY and NOT jQuery (which I know is nothing but Javascript, but I am forbidden from using it for this solution)
With your HTML structure you can try this - DEMO
alert ( document.querySelector( "span" ).firstChild.nodeValue );
you can do it like this. it also works if you have more text after the second span.
<span id="span1">This is Outside Text
<span id="span2">This is Inside Text</span>
</span>
var element = document.getElementById("span1");
var element2 = document.getElementById("span2");
var text = element.textContent.replace(element2.textContent, "");
alert(text);
http://jsfiddle.net/btevfik/y58xJ/
You are looking for the text children (childNodes of type 3):
var children=document.getElementById("mySpan").childNodes,
count=children.length,
text="";
for (var i=0;i<count;i++) {
if (children[i].nodeType==3) {
text+=children[i].nodeValue;
}
}
Live demo: http://jsfiddle.net/aDgPj/
quick question, i know we can change the content of a
<div id="whatEverId">hello one<div> by using:
document.getElementById("whatEverId").innerHTML="hello two";
now, is there a way I can ADD stuff to the div instead of replacing it???
so i can get
<div id="whatEverId">hello one hello two<div>
(using something similar of course)
<div id="whatever">hello one</div>
<script>
document.getElementById("whatever").innerHTML += " hello two";
</script>
Notice that using element.innerHTML += 'content' would empty inputs and textareas to their default, blank state, unclick checkboxes, as well as removing any events attached to those elements (such as onclick, on hover etc.) because the whole innerHTML would be reinterpreted by the browser, which means .innerHTML is emptied and filled again from scratch with the combined content.
If you need to keep the state, you'd need to create a new element (a <span> for instance) and append it to the current element, as in:
let newElement = 'span'
newElement.innerHTML = 'new text'
document.getElementById('oldElement').appendChild(newElement)
document.getElementById("whatEverId").innerHTML = document.getElementById("whatEverId").innerHTML + "hello two" + document.getElementById("whatEverId").innerHTM ;
What jcomeau_ictx suggested is an inefficient way of editing the innerHTML.
Check Ben cherry's PPT http://www.bcherry.net/talks/js-better-faster
The correct way will be detaching the element and making changes to it and then appending it back to the parent node.
Use https://gist.github.com/cowboy/938767 Native javascript from this gist to
detach element.
If you are appending, you can just change your = to a +=
document.getElementById("whatEverId").innerHTML += 'hello two';
If prefixing
document.getElementById("whatEverId").innerHTML = 'hello two' + document.getElementById("whatEverId").innerHTML;
Although I would highly recommend using jQuery or MooTools javascript libraries/frameworks to do this sort of thing. If you're adding tags not just text nodes, then you should use the DOM createElement or one of the aforementioned libraries/frameworks.
You can do it by appending div string like this..
document.getElementById('div_id').innerHTML += 'Hello Two';
I’m using AJAX to append data to a <div> element, where I fill the <div> from JavaScript. How can I append new data to the <div> without losing the previous data found in it?
Try this:
var div = document.getElementById('divID');
div.innerHTML += 'Extra stuff';
Using appendChild:
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
var content = document.createTextNode("<YOUR_CONTENT>");
theDiv.appendChild(content);
Using innerHTML:
This approach will remove all the listeners to the existing elements as mentioned by #BiAiB. So use caution if you are planning to use this version.
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.innerHTML += "<YOUR_CONTENT>";
Beware of innerHTML, you sort of lose something when you use it:
theDiv.innerHTML += 'content';
Is equivalent to:
theDiv.innerHTML = theDiv.innerHTML + 'content';
Which will destroy all nodes inside your div and recreate new ones. All references and listeners to elements inside it will be lost.
If you need to keep them (when you have attached a click handler, for example), you have to append the new contents with the DOM functions(appendChild,insertAfter,insertBefore):
var newNode = document.createElement('div');
newNode.innerHTML = data;
theDiv.appendChild(newNode);
If you want to do it fast and don't want to lose references and listeners use: .insertAdjacentHTML();
"It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation."
Supported on all mainline browsers (IE6+, FF8+,All Others and Mobile): http://caniuse.com/#feat=insertadjacenthtml
Example from https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
If you are using jQuery you can use $('#mydiv').append('html content') and it will keep the existing content.
http://api.jquery.com/append/
IE9+ (Vista+) solution, without creating new text nodes:
var div = document.getElementById("divID");
div.textContent += data + " ";
However, this didn't quite do the trick for me since I needed a new line after each message, so my DIV turned into a styled UL with this code:
var li = document.createElement("li");
var text = document.createTextNode(data);
li.appendChild(text);
ul.appendChild(li);
From https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent :
Differences from innerHTML
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.
Even this will work:
var div = document.getElementById('divID');
div.innerHTML += 'Text to append';
An option that I think is better than any of the ones mentioned so far is Element.insertAdjacentText().
// Example listener on a child element
// Included in this snippet to show that the listener does not get corrupted
document.querySelector('button').addEventListener('click', () => {
console.log('click');
});
// to actually insert the text:
document.querySelector('div').insertAdjacentText('beforeend', 'more text');
<div>
<button>click</button>
</div>
Advantages to this approach include:
Does not modify the existing nodes in the DOM; does not corrupt event listeners
Inserts text, not HTML (Best to only use .insertAdjacentHTML when deliberately inserting HTML - using it unnecessarily is less semantically appropriate and can increase the risk of XSS)
Flexible; the first argument to .insertAdjacentText may be beforebegin, beforeend, afterbegin, afterend, depending on where you'd like the text to be inserted
you can use jQuery. which make it very simple.
just download the jQuery file add jQuery into your HTML
or you can user online link:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
and try this:
$("#divID").append(data);
The following method is less general than others however it's great when you are sure that your last child node of the div is already a text node. In this way you won't create a new text node using appendData MDN Reference AppendData
let mydiv = document.getElementById("divId");
let lastChild = mydiv.lastChild;
if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
lastChild.appendData("YOUR TEXT CONTENT");
java script
document.getElementById("divID").html("this text will be added to div");
jquery
$("#divID").html("this text will be added to div");
Use .html() without any arguments to see that you have entered.
You can use the browser console to quickly test these functions before using them in your code.
Why not just use setAttribute ?
thisDiv.setAttribute('attrName','data you wish to append');
Then you can get this data by :
thisDiv.attrName;