I have a variable with the HTML code:
let htmlDocument = '<div id="buildings-wrapper"> \
<div id="building-info"> \
<h2><span class="field-content">Britney Spears' House</span></h2> \
<div class="building-field"> \
<div class="field-content">9999 Hollywood Blvd</div> \
</div> \
<div class="building-field"> \
<div class="field-content">Building Hours: Mon. 07:00-23:00 Tue.-Fri. 06:30-22:00, Sat. 07:30-18:00, Sun. 12:00-18:00 Holidays - Closed</div> \
</div> \
<div class="building-field"> \
<div class="field-content"><a href="http://www.britneyspears.com">Locate on the stars map</a></div> \
</div> \
</div> \
<div id="building-image"> \
<div class="field-content"><img src="../../../../ssc.adm.britneyspears.com/classroomservices/image/viewimage?userEvent=ShowBuildingImage&buildingID=britneyspears" alt="Image of BritneySpears"></div> \
</div> \
</div>';
I want to traverse the variable and store this section of HTML in a separate variable:
<div class="field-content">9999 Hollywood Blvd</div>
This is what I have so far:
public traverseHTML(htmlDocument: any): any {
let htmlBlock: any;
let divs: any = htmlDocument.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
if (divs[i].getAttribute("id") == "field-content") {
htmlBlock = divs[i];
}
}
return htmlBlock;
}
I'm sure there are all sorts of issues with my function but I can't get to them cause I can't even get past the second line. I get an error saying htmlDocument.getElementsByTagName
isn't a function. How do I iterate thru the HTML by div?
Please note I can't use JQuery due to project specs.
EDIT:
I'm getting document is not defined
when I try to document.createElement('div')
and DOMParser is not defined when I try to create a DOMParser. Am I setting up the class incorrectly? This is the code for the entire class:
import parse5 = require('parse5');
import {ASTNode} from 'parse5';
export default class DSController {
//private parser: DOMParser;
constructor() {
//this.parser = new DOMParser();
}
public traverseHTML(htmlDocument: any): any {
let parser = new DOMParser();
let parsed: any = parser.parseFromString(htmlDocument, "text/html");
let selectParsed: any = parsed.querySelectorAll('field-content')[1];
console.log(selectParsed);
return selectParsed;
/* let element = document.createElement("div");
element.innerHTML = htmlDocument;
console.log(element.querySelectorAll(".field-content")[1]); // <div class="field-content">9999 Hollywood Blvd</div>
*/
}
public parseHTML(): any {
//let document: parse5.ASTNode;
return;
}
}