0

I need to retrieve text from inner element. With php it so easy to use Xpath. how about in javascript? I need to retrieve from specific element with specific id too. the request under code below. Let say it doesnt problem with CORS. i installed chrome extension to solve CORS.

<html>
<head>
</head>
<body>


<script>


   fetch('https://alexistogel1.blogspot.com/2019/08/post-tak-penting.html')
    .then(function (response) {
      return response.text();
    })
    .then(function (html) {
      var element = document.evaluate( "//div[@id='post-body-6034358444211110141']" ,document, null, XPathResult.ANY_TYPE, null );
      console.log(element);
    });
</script>
</body>
</html>
4
  • Are you forced to use XPath? Commented Aug 21, 2019 at 11:10
  • no, all solution is accept. Commented Aug 21, 2019 at 11:12
  • Shouldn't the second argument on document.evaluate be html? Commented Aug 21, 2019 at 11:28
  • @EmielZuurbier i tried it too, it gives error Failed to execute 'evaluate' on 'Document': parameter 2 is not of type 'Node' Commented Aug 21, 2019 at 11:30

1 Answer 1

1

Use a DOMParser to convert your string to a document.
Now you can use the document to select the element inside it with the help of getElementById.

fetch('https://alexistogel1.blogspot.com/2019/08/post-tak-penting.html')
    .then(function (response) {
        return response.text();
    })
    .then(function (text) {
        const parser = new DOMParser();
        return parser.parseFromString(text, 'text/html');
    })
    .then(function (html) {
        var element = html.getElementById('post-body-6034358444211110141');
        console.log(element.innerHTML);
    });
Sign up to request clarification or add additional context in comments.

4 Comments

i gives error like enum. then i change application/html to text/html to fix. but give other error when itry console log(element.stringValue);
stringValue is no property that element contains. You'll want to get the innerHTML property to get the values inside an element. I've updated the answer.
Xpath solution return undefined.
I've removed the XPath answer since it does not seem to work. getElementById is a native JavaScript function which is the more preferable way to select an element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.