Javascript for fetching the contents of an web page? - javascript

I want to fetch the value of class .cell-hover through javascript and it should print the value which is present in double quotes. So far I tried:
var phonenumbers = document.getElementsByClassName('cell-hover');
document.write(phonenumbers);
but its printing [object HTMLCollection], and I want to print the exact value.
Attached Snapshot:

document.getElementsByClassName('cell-hover'); will return an array of elements with class name cell-hover.Loop through that and print the result.For the content inside that class use innerHTML. The innerHTML will return DOM content as a String
You can also use node.textContent; if you know that your div contains only text
Here in the snippet i have printed the content of the first element with class name cell-hover
var phonenumbers = document.getElementsByClassName('cell-hover');
document.write( phonenumbers[0].innerHTML);
<div class="cell-hover">
2637145689
</div>
var phonenumbers = document.getElementsByClassName('cell-hover');
for(var i=0; i < phonenumbers.length ; i++){
document.write( phonenumbers[0].textContent );
}
<div class="cell-hover">
2637145689
</div>

One liner:
document.write(document.querySelector('.cell-hover').innerHTML);

document.write(document.querySelector('.cell-hover').innerText);

Related

innerText is concatenating words

So HTML.outerHTML outputs <td><p><b>Ranges of</b><br><b>Exercise</b> <b>Prices</b></p></td>
HTML.innerText outputs "Ranges ofExercise Prices"
HTML is an HTMLElement
The result I'm trying to get is "Ranges of Exercise Prices". innerText and textContent both give the same incorect result. How can I prevent the concatenation of strings with those line break tags present? (Can't change the HTML)
This is a whack a mole way, but you can replace the br element with a space so it will show up as a space when you replace it.
const temp = document.querySelector('.test').innerHTML;
const cloned = (new DOMParser()).parseFromString(temp, 'text/html');
cloned.documentElement.querySelectorAll('br').forEach(function (br) {
br.replaceWith(' ');
});
console.log(cloned.body.textContent);
<div class="test"><p><b>Ranges of</b><br><b>Exercise</b> <b>Prices</b></p></div>
function getTextContent() {
alert(document.getElementById("demo").textContent)
}
<p id="demo"><b>Ranges of </b><br><b>Exercise</b> <b>Prices</b></p>
<button onclick="getTextContent()">Get textContent</button>
You can use textContent to get only text inside the p tag

Compare string with HTML text

I have a string of text that I want to compare with another string that has HTML code. The problem is that the text I need to compare it to in the HTML code is within different tags. Also, if the string exists in the HTML code then I want to wrap it inside a <mark> tag.
This is the example I am using:
var html = "<h1>This is a heading</h1><div class="subtitle">and this is the subheading</div><p class="small">this is some example text</p>";
var lookup = "is a heading and this is the subheading this is some";
var finalHtml = ""; //will contain new html
//Need to do some comparison and then add a <mark> tag around found string.
console.log(finalHtml);
//This should print "<h1>This <mark>is a heading</h1><div class="subtitle">and this is the subheading</div><p class="small">this is some</mark> example text</p>"
I am using Javascript/Jquery to do this.
This will only help to search your lookup within html (i.e., no marking). I have removed tags-spaces & then checked.
var html = '<h1>This is a heading</h1><div class="subtitle">and this is the subheading</div><p class="small">this is some example text</p>';
//remove html tags & spaces.
cleanHtml = html.replace(/<\/?[^>]+(>|$)/g, "").replace(/\s/g,"");
var lookup = "is a heading and this is the subheading this is some";
lookup = lookup.replace(/\s/g,'');
if(cleanText.includes(lookup)){
//match found
}

how to put element into <div> by innerHTML or other ways?

This is my code:
var turn = 1;
var boardPiece;
var piece = [];
function init() {
boardPiece = document.getElementById("pages");
while (boardPiece.firstElementChild) {
if (typeof boardPiece.firstElementChild.id != 'undefined') {
piece.push(boardPiece.firstElementChild);
}
boardPiece.removeChild(boardPiece.firstElementChild);
}
document.getElementById("content").innerHTML = piece[0]; //My problem is here
}
init();
<div id="content">
</div>
<div id="pages">
<div id="page1" class="page">
...
</div>
<div id="page2" class="page">
...
</div>
</div>
The result is a text
[object HTMLDivElement]
not an element.
What's wrong with my .innerHTML? And what is typeof piece[0]? Is it text?
You need to replace your:
document.getElementById("content").innerHTML = piece[0];
with:
document.getElementById("content").innerHTML = piece[0].innerHTML;
What you are trying to do atm is to insert element (which is an object) as a plain text.
You need to use the .innerHTML along with your piece[0] variable like,
document.getElementById("content").innerHTML = piece[0].innerHTML;
Working Fiddle: https://jsfiddle.net/gs0yy50t/
Hope this helps!
The issue is that the type of piece[0] is not a string, but a HTML element. For that reason, in order to assign it to the content's innerHTML (which is a string), JavaScript is implicitly calling the piece[0].toString() method.
When calling the toString() method in HTML nodes (like most non-string objects in JavaScript), it returns a string representing the type of the object.
If you need to add the element piece[0] as child of content, then you should do:
document.getElementById("content").innerHTML = piece[0].outerHTML;
However, if what you need is to copy the content of one element into another, you should use the property innerHTML instead:
document.getElementById("content").innerHTML = piece[0].innerHTML;
Basically, both properties are strings with the HTML code of the element but outerHTML includes the element itself in the root.

how to get value of an element using getElementById and getElementsByTagName together

I am trying to prettyprint the value of <pre> element for which I will be getting either xml or JSON as string, so I am trying to get the value first and then test if it is xml or json and call respective prettyprint methods here is my code ...
function showData(attName) {
var attData = document.getElementById(attName).getElementsByTagName('pre')[0];
alert(attData);
// once I get the value would like to test whether it is xml or json
//if (attData contains xml test condition )
prettyPrint.xml(attData);
else prettyPrint.json(attData);
document.getElementById('Details').style.display='none';
document.getElementById(attName).style.display='block';
}
So the showData will be called whenever I click on View link in the below code ..
<div id="Details" class="body">
View
</div>
<div id="${attachmentName}" style="display:none; margin-left:60px; margin-top:5px;position:absolute;background-color:#F8F8F8;padding:10px" >
<h1>${attachmentName}:${attachmentId}</h1>
<h5 style="color: #FF0066;"> [X Close] </h5> <br/>
<pre class="prettyprint">${attachmentData}</pre>
</div>
In alert I am getting [object HTMLPreElement] but not sure how to make it to string, so I have also tried ...
var objectHTMLCollection = document.getElementById(attName).getElementsByTagName('pre')[0],
string = [].map.call( objectHTMLCollection, function(node){
return node.textContent || node.innerText || "";
}).join("");
alert (objectHTMLCollection);
But still getting as HTMLPreElement...
I have tried the JQuery jQuery('#'+attName).find('.prettyprint').data(); but got the result as [object Object] .
I don't have much exposure in the JavaScript,may be I am not doing it in right way. It would be great if anyone can help on this.
Add .innerHTML - should work, get rid of the complicated mapping functions that are meant to work with multiple <pre> tags at once.
var attData = document.getElementById(attName).getElementsByTagName('pre')[0].innerHTML;
alert(attData);
If you're using jQuery:
var text = $("#" + attName + " pre:first").text();
That gets you the text content of the element.
Your last js snippet is close, but you're calling map on a non-array object, and passing the wrong var to alert(). To find all 'pre' elements:
var objectHTMLCollection = document.getElementsByTagName('pre');
var str = [].map.call( objectHTMLCollection, function(node){
return node.textContent || node.innerText || "";
}).join("");
alert (str);
If you are actually only looking for one 'pre' element:
var htmlObject = document.getElementById(attName);
var str = htmlObject.textContent || htmlObject.innerText || "";
alert (str);
Remember, an element's id is unique, so there's no point in querying by id, and tag name.

getElementBy ID not returning for label tag

getElementById does not return any value. My objective is I have a text content and
upon a action I have to replace the value of the text. I use labels to display.
Is there any better way to display such modified text, I dont want to use textbox.
<% for(int i=0; i<lines.length;i++) {
if(lines[i].contains(" ")) { %>
<label id='idkey<%=i%>' name='key1<%=i%>'>ABC</label>
<%
}
} %>
for(j=0; j<len; j++){
var lblElement = document.getElementById('idkey'+j).innerText="ddd";
alert(lblElement);
}
Re hi,
I think your Id is wrong, innerText work properly with http://jsfiddle.net/mPc2E/
Be carreful, innerText return the value of you new text, not the modified tag.
document.getElementById('lab').innerText = " toto"
Try
document.getElementById('idkey'+j).innerHTML = 'ddd';
Demo here
The line var lblElement = document.getElementById('idkey'+j).innerText="ddd"; does not set lblElement equal to the element - but rather equal to the text "ddd".
Try the following in stead:
for(j=0; j<len; j++){
var lblElement = document.getElementById('idkey'+j);
lblElement.innerText="ddd";
alert(lblElement);
}
Note: This assumes that the len variable contains the correct value

Categories

Resources