How to get Value from html string? - javascript

I have a html string like this which response from API:
const response = `
<html>
<head>
<title></title>
</head>
<body>
<code>Value I want to get<br></code>
</body>
</html>
`;
So the content maybe dynamic but the tag <code> is unique. I want to have some more solutions on this to see what is the best solution.

You could use a DOMParser to convert your HTML string into a Document object which you can then use querySelector() to get your desired value:
const response = `
<html>
<head>
<title></title>
</head>
<body>
<code>Value I want to get<br></code>
</body>
</html>
`;
const {body} = new DOMParser().parseFromString(response, 'text/html');
const value = body.querySelector('code').innerText; // find <code> tag and get text
console.log(value);

Related

Get value from string via xpath in javascript

I have a html page as string like below;
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
and I want to get value from that string via xPath. Xpath like below;
/html/body/p
Result has to be ;
This is a paragraph.
I solved my problem as below. I wrote a method which is convert html to element.
function htmlToElement(html) {
var doc = new DOMParser().parseFromString(html, "text/html");
return doc;
}
I got value like below.
var doc = htmlToElement(htmlString);
xPath = "/html/body/p";
var value = doc.evaluate(xPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext().innerHTML;

Selecting specific part of an HTML text

I have a function that returns some HTML fragment that I store in a variable called data, with its whole structure. What I want is to extract from it some of those parts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script id="hello">
</script>
</head>
<body>
</body>
</html>
For example, I want to get the body and save it in a new variable:
var body = data.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
Where data is the HTML text as a string that the original function is returning.
Is there any way I could save an specific script, from its ID (in this case with id = hello), and save it in another variable??
Thank you very much
var newVar = $("#hello").html();
Let's suppose you have an HTML string in a variable, for example
var foo = '<body><span>bar</span></body>';
Now, let's initialize a parser, to convert this into HTML:
var parser = new DOMParser();
var doc = parser.parseFromString(foo, "text/html");
Now, you can read anything from foo, as it is converted into HTML:
document.getElementsByTagName("body")[0].innerHTML = doc.querySelectorAll("body")[0].innerHTML;
$html = document.querySelector("body").innerHTML;
$hello = document.getElementById("hello").innerHTML;
console.log($html);
console.log($hello);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script id="hello">
// script data
</script>
</head>
<body>
</body>
</html>

How to create an element in JavaScript, under a specific HTML tag

I want to create a paragraph element from JavaScript, but I want it to be placed under a certain tag in HTML. How would I do this?
Try with this.
var element = document.createElement("p"); //div,span,h1
element.appendChild(document.createTextNode('the text you want if you want'));
document.getElementById('theElementToAppend').appendChild(element);
<html>
<head>
<title>appendChild() Example</title>
<script type="text/javascript">
function appendMessage() {
var oNewP = document.createElement("p");
var oText = document.createTextNode("www.java2s.com");
oNewP.appendChild(oText);
document.body.appendChild(oNewP);
}
</script>
</head>
<body onload="appendMessage()">
</body>
</html>

Load and parse xml based on string, IE

Im trying to parse an xml string in IE based on the following example: http://dean.edwards.name/weblog/2006/04/easy-xml/
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function(){
var xml = document.createElement("xml");
xml.src = '<test><node1>Test</node1></test>';
document.body.appendChild(xml);
var xmlDocument = xml.XMLDocument;
document.body.removeChild(xml);
});
</script>
</head>
<body>
</body>
</html>
Fiddle
However, its not working. I get no errors, but nothing is happening.
Is there any way to generate an XML file on the client side in IE based on a valid xml string? Is activeX the only option?
Thanks in advance
A variant I have working is not to create an xml object, but create a wrapper div instead:
<script type="text/javascript">
$(function(){
var div, xmlDocument;
div = document.createElement('div');
div.innerHTML = '<xml><test><node1>Test</node1></test></xml>';
document.body.appendChild(div);
xmlDocument = div.firstChild.XMLDocument;
document.body.removeChild(div);
});
</script>
ActiveX is certainly one option. The code would be something like:
var xml = '<test><node1>Test</node1></test>';
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xml);
alert(xmlDoc.documentElement.nodeName);

Why doesn't JSON.parse work?

Why doesn't JSON.parse behave as expected?
In this example, the alert doesn't fire:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Testing JSON.parse</title>
<script type="text/javascript" src="js/json2.js">
// json2.js can be found here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
</script>
<script type="text/javascript">
function testJSONParse()
{
var text = '[{"a":"w","b","x"},{"a":"y","b":"z"}]';
alert(JSON.parse(text));
}
window.onload = testJSONParse;
</script>
</head>
<body>
</body>
</html>
In firefox, the Error Console says "JSON.parse". Not very descriptive..
This is a simplification of a problem I have which uses AJAX to fetch data from a database and acquires the result as a JSON string (a string representing a JSON object) of the same form as text in the example above.
Your JSON is not formatted correctly:
var text = '[{"a":"w","b","x"},{"a":"y","b":"z"}]';
^-- This should be a ':'
It should be:
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
error in typing
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
//below is correct one
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
alert(JSON.parse(text));

Categories

Resources