Get value from string via xpath in javascript - 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;

Related

How to get Value from html string?

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

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>

Difficulty Using JavaScript Highlight Plugin

I'm trying to use a plugin called mark.js (https://markjs.io/). From my perspective I'm doing everything they say to, but the Chrome console keeps returning the error:
My html code is as follows:
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/7.0.0/mark.min.js"></script>
<script src="highlighter.js"></script>
</head>
<body>
<p>hello i am rob</p>
</body>
</html>
My javascript code, in a file called "highlighter.js", is as follows:
var context = document.querySelector(".context");
var instance = new Mark(context);
instance.mark("rob");
A screenshot from the plugin website:
I don't know what I'm doing wrong. Thanks for the help!
You have to have a class name of .context in order for it to recognise that as the context.
var context = document.querySelector(".context"); // <p> tag class name
var instance = new Mark(context);
instance.mark("rob");
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/7.0.0/mark.min.js"></script>
<!-- notice the class="context" on the paragraph tag -->
<p class="context">hello i am rob</p>
https://jsfiddle.net/e6yzpton/
To mark the entire document you could do something like this:
var context = document.querySelector("body");
var instance = new Mark(context);
var paragraph = document.getElementsByTagName("p")[0].innerHTML;
instance.mark(paragraph);
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/7.0.0/mark.min.js"></script>
<body>
<p>and it was all yellow</p>
</body>
https://jsfiddle.net/e6yzpton/2/

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>

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