Reputation: 2525
I am trying to pull text from a web page with the below code:
const theHtml = document.children[0];
function showThePage(htmlObject){
for(var key in htmlObject){
console.log(key);
console.log(htmlObject.hasOwnProperty(key));
if(htmlObject.hasOwnProperty(key))
{
if(htmlObject.key.hasOwnProperty('textContent')){
console.log(key.textContent);
}
}
}
}
showThePage(theHtml);
Something screwy is going on with the properties/children. When I check for the property by the name of each key, it is never true (execution never enters the if statement)... meaning the htmlObject has no properties by the name of the given keys. However, when I examine the DOM/DevTools, the properties are in fact listed on the HtmlObject. Am I missing something?
Upvotes: 0
Views: 49
Reputation: 14649
You need to use square brackets to access the property on the htmlObject that is equal to the value of key
if(htmlObject[key].hasOwnProperty('textContent')){
// ...
}
In your case, you're looking to check weather the value of key
is in the htmlObject
The string literal "key"
is perhaps equivalent to key in the case of dot notation vs [] notation.
Upvotes: 2
Reputation: 4038
Consider using document.querySelectorAll()
.. you can use any jQuery/CSS selector to return only the elements you want to pull text from.
var elements = document.querySelectorAll('*');
for ( var i = 0 ; i < elements.length ; ++i ) {
var key = elements[i];
if ( key && key.textContent ) {
console.log(key,key.textContent);
}
}
Upvotes: 1