javascript getElementById and convert it to String - javascript

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.

Related

How can I extract the textContent from an HTML string without creating a HtmlElement?

I recently came across an issue where I need to strip the html tags from the data before displaying it on screen.
The data came this way:
<p><span style="color: rgb(68, 68, 68);">Sample data which i want to get.</span></p>
What have I tried
In order to solve this issue, I created a div, added the html with innerHtml and extract the text with textContent.
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
The above code has been taken from stackoverflow.
The problem
I'm concerned if this is the correct thing to do, as this is creating extra divs every time we call the strip function.
The question
Is there any better way to accomplish this?
Maybe this helps you.
The following example uses another approach. Instead of extracting text it removes tags using a regular expression assuming your data is a html string.
Limitation: This regex doesn't work if your text content includes < or > characters. If that's an issue you need to modify the regex.
var str = '<p><span style="color: rgb(68, 68, 68);">Sample data which i want to get.</span></p>';
var str2 = '<p><span style="color: rgb(68, 68, 68);">Sample data which i <strong>want</strong> to get.</span></p>';
function strip(html) {
return html.replace(/<\s*[^>]*>/gi, '');
}
console.log(strip(str));
console.log(strip(str2));
You don't have to make a new element every time. Make a class and create the div once and store it as an instance property. Then every time you need to strip some HTML you just overwrite the existing contents with the new contents and return the text content.
class Stripper
{
constructor() {
this._target = document.createElement("div")
}
strip(html) {
this._target.innerHTML = html
return this._target.textContent || this._target.innerText || ""
}
}
const stripper = new Stripper()
console.log(stripper.strip(/* your html */))
Hi to get the HTML of specific div you can use ‘refs’
React refs work like id in jquery with the refs you can easy get the content or any other param of that div
There is an alternative to get the text from an HTML string: DomParser.
It has decent support for all browsers (Check support here)
Here is an example how you can use it:
function strip(html){
var doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || "";
}
Benefits of DomParser over your solution is that DomParser API can be instantiated only once, whereas your solution has to create a div element everytime you call the strip function.

Finding and replacing html tags conditionally from an html string

I have access to an html string in which I want to search for a specific set of values. So lets say I want to match something from an array...
var array1 = [value1, value2, value3]
If I find value1 in the html string, i want to add a highlight class to that value so it gets highlighted.
var str = htmlString
var res = str.replace('<thead>','<thead class="highlight">');
htmlString = res
Using this i can highlight all the theads, but how could I write it so that I only highlight the theads that contain one of those array values inside of it?
Here's a solution for browser that parses the HTML string into a DOM element, query the DOM tree and manipulate the classList of each selected element, then returns the HTML as a string.
function addClassToElementsByTagName(html, tagName, className) {
var tempElement = document.createElement('div');
tempElement.innerHTML = html;
var elements = tempElement.querySelectorAll(tagName);
elements.forEach(function(element) {
element.classList.add(className);
});
return tempElement.innerHTML;
}
var htmlString = '<table>\n\t<thead>\n\t<tr>\n\t\t<th>Column 1</th>\n\t\t<th>Column 2</th>\n\t\t<th>Column 3</th>\n\t</tr>\n\t</thead>\n</table>';
var result = addClassToElementsByTagName(htmlString, 'thead', 'highlight');
console.log(result);
Gotchas
Keep in mind that element.querySelectorAll() and element.classList.add() are not universally supported. Check out caniuse.com for information regarding each feature.
Also, this is completely dependent on how the browser parses your HTML. If the HTML fails to parse or parses incorrectly, you will experience problems. The .innerHTML property also makes no guarantee that the whitespace provided in the original string will be preserved in the result.

Find DOM element in text content using javascript

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

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;

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

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

Categories