Please push me towards a duplicate of this question if possible. I've looked everywhere but can't seem to find it.
How do I do a getElementById on text content?
var test = '<div id="thisDiv">HI</div>';
How do I select thisDiv if it's not a part of the DOM?
Create an element, set your string as its innerHTML and then search inside that ...
Something like
var test = '<div id="thisDiv">HI</div>';
var element = document.createElement('DIV');
element.innerHTML = test;
alert(element.textContent);
(changed the initial outerHTML as you can only maintain a reference to the originaly created element, and not the new one that is created by the new html)
For getting the text value inside your tags, use RegEx:
var re = new RegExp("<(.|\n)*?>", "g");
var content = test.replace(re,"");
You could create a temporary DIV and populate it with your string. Even then, your ability to access it would be limited. Add it to the DOM to access it using getElementById.
var div = document.createElement('div');
div.innerHTML = '<div id="thisDiv">HI</div>';
alert(div.firstChild);
To avoid creating that extra element, we could just add it to the body...
var test = '<div id="thisDiv">HI</div>';
document.querySelector('body').innerHTML = test;
console.log(document.getElementById('thisDiv'));
Obligatory Fiddle
Getting just the text...
console.log(document.getElementById('thisDiv').textContent); // returns HI
Related
I have a string named stringElement and its value is anchor tag but in string not as node element.
How to get the inner text of that tag in pure js?
How it was done using jQuery:
var stringElement = "<a>1</a>";
nodeElement div = document.createElement('div');
$(div).append(stringElement);
var nodeElement2 = $(div).find("a")[0];
var text = $(nodeElement2).text();
text value is 1 <=== This is the target
EDIT: My bad, I found the answer in another question and this should be marked as duplicate.
Here is the questions link:
Converting HTML string into DOM elements?
Here is the answer link that worked for me:
https://stackoverflow.com/a/3104237/2648837
try this,usetextContent or innerText
var str = "<a>1</a>";
var div=document.createElement('div');
div.innerHTML=str;
console.log(div.children[0].textContent);
console.log(div.children[0].innerText);
I created a constructor that will handle a custom list control. I created a method in order to allow the user to add elements to the list, and I need to assign event handlers to the click events of the list elements (divs).
A simplified version of the code is here. The list elements are created using the innerHTML property and a string template upon which I substitute specific parts. Later I get the element by it's id and assign it a function in closure:
function prueba(){
var plantilla = '<div id="«id»">«texto»</div>';
var f = function(nombre){
return function(){console.log('mi nombre es ' + nombre)};
};
this.agregar = function(id, texto){
var tmp = plantilla.replace('«id»', id);
tmp = tmp.replace('«texto»', texto);
document.body.innerHTML += tmp;
document.getElementById(id).onclick = f(id);
};
};
The problem is that, apparently, the event handler is unasigned to previous created divs, so is only retained by the last one, as it can be tested with the following code:
var p = new prueba;
p.agregar('i1', 'texto1');
console.log(document.getElementById('i1').onclick.toString());//shows the function code
p.agregar('i2', 'texto2');
console.log(document.getElementById('i2').onclick.toString());//shows the function code
console.log(document.getElementById('i1').onclick.toString());//returns 'null' error
p.agregar('i3', 'texto3');
console.log(document.getElementById('i3').onclick.toString());//shows the function code
console.log(document.getElementById('i2').onclick.toString());//returns 'null' error
This happens in Iceweasel as well as in Chromium. It does NOT happen when I add 'onclick = f(«id»)' in the template (which I cannot do here because of the assigned function scope), and neither happens if I use document.createElement. What am I doing wrong?
You destroy elements previously created when you do this:
document.body.innerHTML += tmp;
Instead use insertAdjacentHMTL() if you want to append using HTML markup.
document.body.insertAdjacentHTML("beforeend", tmp);
Now instead of going through this destructive process...
serialize the existing DOM nodes to HTML
concatenate the new HTML fragment to the serialized nodes
destroy the old nodes
recreate the nodes with the new nodes
...it simply creates the new content and places it before the close of the body element.
Basically, remove element.innerHTML += ... from your coding practices. It's never necessary, it's inefficient and it causes problems like what you've described.
FYI, the .insertAdjacentHTML() method receives 4 different string possibilities as the first argument. Each one designates a position relative to the element on which you're calling it.
The strings are...
"beforebegin"
"afterbegin"
"beforeend"
"afterend"
The labels are pretty self-explanatory. They position the new content before the current element, inside the current element at the beginning, inside the current element at the end, or after the current element, respectively.
Your full code will look like this, which I shortened a bit too since the tmp really isn't needed here:
function prueba(){
var plantilla = '<div id="«id»">«texto»</div>';
var f = function(nombre){
return function(){console.log('mi nombre es ' + nombre)};
};
this.agregar = function(id, texto){
document.body.insertAdjacentHTML("beforeend",
plantilla.replace('«id»', id)
.replace('«texto»', texto));
document.getElementById(id).onclick = f(id);
};
};
I have the following line in my jsp file:
var option = document.createElement('<option value="NO">');
Not sure why this gives me InvalidCharacterError.
Any alternatives?
You can use this code to add to your tag.
var myoption = document.createElement("option");
myoption.setAttribute("value", "carvalue");
var text = document.createTextNode("maruti");
myoption.appendChild(text);
document.getElementById("mySelect").appendChild(myoption);
There was a change in DOM implementation.
Before, you could create a new element with the code inside, for instance:
BAD
var anElement = document.createElement("StackOverflow")
This implementation now, returns this ‘InvalidCharacterError’.
What you must do now is to create the element and to populate it using the innerHTML attribute or the different specific attributes for any node.
GOOD
var anElement = document.createElement("a")
anElement.innerHTML = ("StackOverflow")
This might seem a little simple, but i've tried many ways & non of them are working as expected.
i have values coming in from an ajax call, & i am displaying these to a <table>.
the data will not be seen at first (css - display:none) but onclick involves a function which displays a dialog of said data.
writing out the data in these ways does not work:
var text = "Example Data<br>";
var text = document.createTextNode("Example Data" + document.createElement('br'));
var text = document.createTextNode("Example Data");
text += document.createElement('br');
The latter outputs [object Text][object HTMLBRElement]
How do i write this correctly??
You can't concatenate node objects (trying to do so with + will convert them to strings first).
Find the element you want to append the nodes you've created, and call appendChild on it repeatedly.
var text = document.createTextNode("Example Data");
someElement.appendChild(text);
someElement.appendChild(document.createElement('br'));
You need to append the line break as an HTML element "createElement" as it is an HTML element.
var text = 'test';
var newtext = document.createTextNode(text),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
p1.appendChild(document.createElement('br'));
p1.appendChild(document.createTextNode('newline displayed'));
Try
var p = document.createElement("p");
p.innerHTML = "Example Text<br>";
You can try this:
Give the table an id
Append html response to the table by using $('#tableid').html(responsedata);
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.