Find specific div with RegEx and print content - javascript

I'm trying to pull some text from an external website using this script.
It works perfectly, but it gets the entire page. I want to take only the content inside a specific div with the class 'content'. The entire page is put inside the variable 'data', and then this function is created to strip some tags:
function filterData(data){
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
How would I go about finding the div with the class 'content' and only viewing the content inside that?
UPDATE: Sorry about using RegExes — can you help me to get the content without using RegEx? So, this is my HTML file:
erg
<div id="target" style="width:200px;height:500px;"></div>
<div id="code" style="width:200px;height:200px;"></div>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
if(url.match('^http')){
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function(data){
if(data.results[0]){
var tree = string2dom(data.results[0]);
container.html($("div.content", tree.doc));tree.destroy();
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
}
);
} else {
$('#target').load(url);
}
}
function filterData(data){
return tree;
}
});
</script>

Try something like this:
var matches = data.match(/<div class="content">([^<]*)<\/div>/);
if (matches)
return matches[1]; // div content

try this:
<div\b[^>]*class="content"[^>]*>([\s\S]*?)<\/div>

Here try this :
<div[^>]*?class='content'[^>]*?>(.*?)</div>
Captured reference /1 will have your content. Although you shouldn't be doing this with regexes :)

this may help you:
var divtxt = match(/<div[^>]*class="content"[^>]>.*<\/div>/);
but it may stop at the wrong .
you should use jquery or prototype to make it a dom-object and use selectors to find the right div.
using jquery you would do something like:
var divtxt = $(data).find(".content").first().html();
remember to load the jquery library first.

Related

How to select/hide elements inside an object of type "text/html" using javascript [duplicate]

I'm using the object tag to load an html snippet within an html page.
My code looks something along these lines:
<html><object data="/html_template"></object></html>
As expected after the page is loaded some elements are added between the object tags.
I want to get those elements but I can't seem to access them.
I've tried the following
$("object").html() $("object").children() $("object")[0].innerHTML
None of these seem to work. Is there another way to get those elements?
EDIT:
A more detailed example:
consider this
<html><object data="http://www.YouTube.com/v/GGT8ZCTBoBA?fs=1&hl=en_US"></object></html>
If I try to get the html within the object I get an empty string.
http://jsfiddle.net/wwrbJ/1/
As long as you place it on the same domain you can do the following:
HTML
<html>
<object id="t" data="/html_template" type="text/html">
</object>
</html>
JavaScript
var t=document.querySelector("#t");
var htmlDocument= t.contentDocument;
Since the question is slightly unclear about whether it is also about elements, not just about the whole innerHTML: you can show element values that you know or guess with:
console.log(htmlDocument.data);
The innerHTML will provide access to the html which is in between the <object> and </object>. What is asked is how to get the html that was loaded by the object and inside the window/frame that it is producing (it has nothing to do with the code between the open and close tags).
I'm also looking for an answer to this and I'm afraid there is none. If I find one, I'll come back and post it here, but I'm looking (and not alone) for a lot of time now.
No , it's not possible to get access to a cross-origin frame !
Try this:
// wait until object loads
$('object').load(function() {
// find the element needed
page = $('object').contents().find('div');
// alert to check
alert(page.html());
});
I know this is an old question, but here goes ...
I used this on a personal website and eventually implemented it in some work projects, but this is how I hook into an svg's dom. Note that you need to run this after the object tag has loaded (so you can trigger it with an onload function). It may require adaptation for non-svg elements.
function hooksvg(elementID) { //Hook in the contentDocument of the svg so we can fire its internal scripts
var svgdoc, svgwin, returnvalue = false;
var object = (typeof elementID === 'string' ? document.getElementById(elementID) : elementID);
if (object && object.contentDocument) {
svgdoc = object.contentDocument;
}
else {
if (typeof object.getSVGDocument == _f) {
try {
svgdoc = object.getSVGDocument();
} catch (exception) {
//console.log('Neither the HTMLObjectElement nor the GetSVGDocument interface are implemented');
}
}
}
if (svgdoc && svgdoc.defaultView) {
svgwin = svgdoc.defaultView;
}
else if (object.window) {
svgwin = object.window;
}
else {
if (typeof object.getWindow == _f) {
try {
svgwin = object.getWindow();//TODO look at fixing this
}
catch (exception) {
// console.log('The DocumentView interface is not supported\r\n Non-W3C methods of obtaining "window" also failed');
}
}
}
//console.log('svgdoc is ' + svgdoc + ' and svgwin is ' + svgwin);
if (typeof svgwin === _u || typeof svgwin === null) {
returnvalue = null;
} else {
returnvalue = svgwin;
}
return returnvalue;
};
If you wanted to grab the symbol elements from the dom for the svg, your onload function could look like this:
function loadedsvg(){
var svg = hooksvg('mysvgid');
var symbols = svg.document.getElementsByTagName('symbol');
}
You could use the following code to read object data once its loaded completely and is of the same domain:
HTML-
<html>
<div class="main">
<object data="/html_template">
</object>
</div>
</html>
Jquery-
$('.main object').load(function() {
var obj = $('.main object')[0].contentDocument.children;
console.log(obj);
});
Hope this helps!
Here goes a sample piece of code which works. Not sure what the problem is with your code.
<html>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var k = $("object")[0].innerHTML;
alert(k);
$("object")[0].innerHTML = "testing";
});
</script>
<object data="/html_template">hi</object>
</html>
UPDATED
I used this line of Javascript to change the value of a input filed inside an iFrame, taken from How to pick element inside iframe using document.getElementById:
document.getElementById('iframeID').contentWindow.document.getElementById('inputID').value = 'Your Value';
In your case, since you do not have a frame, and since you want to get and not set the value, log it for example with:
console.log(document.getElementById('object').value);
And if you guess or choose an element:
console.log(document.getElementById('object').data);

Email current page button, include part of div

I want to get not just the title and the url from my page when using the recomment by email button, but also part of the content.
I have this function:
function emailCurrentPage(){
var doc = window.document;
var requested_div = document.getElementById('single_page');//the div is called single_page
var requested_div_html = requested_div.innerHTML;
window.location.href="mailto:?subject="+document.title+"&body="+escape(window.location.href)+doc.requested_div_html;
}
</script>
The issue is that I get undefined from doc.requested_div_html. Link and title work well.
I think the error is that doc.requested_div_html is undefined, since you stored the HTML of the requested div in requested_div_html, not doc.request_div_html. It's just wrong variables.
I finally solved it like this:
function emailCurrentPage(){
var log = $('#single_page').find('p')[ 0 ];
var requested_div = log.innerHTML;
window.location.href="mailto:?subject="+document.title+"&body="+"URL Articol: "+escape(window.location.href)+" - Incipit articol:"+requested_div;
}
I didn't need the doc element because it is already said window.location

How can I dynamically add a class to 'body' using JavaScript only for the home page?

I added this to the head, but it's not working:
<script>
var xpathname = (window.location.pathname);
if (xpathname ==('/')) {
$('body').addClass('home');
}
</script>
The site is here: http://xotdr.unxpr.servertrust.com/
Volusion doesn't allow developers to code freely so there are a lot of workarounds that I need to implement, unfortunately.
Edit: I want the class to show only on the home page body.
Since you added this to the head you need to execute this snippet when body tag is available:
$(function() {
var xpathname = window.location.pathname;
if (xpathname == '/') {
$('body').addClass('home');
}
});
<script>
var bodyclass=document.createAttribute("class");
bodyclass.value="home";
document.getElementsByTagName("body")[0].setAttributeNode(bodyclass);
</script>
Give this a try
var b = document.getElementsByTagName('body')[0];
b.className += 'home';
I know it's a old post, but the question will remain useful.
var xpathname = (window.location.pathname);
var ndeBody = document.getElementsByTagName("body")[0];
if (xpathname ==('/')) {
ndeBody.classList.toggle("home");
}
else{
ndeBody.classList.toggle("home");
}
When I go to that URL you have syntax error:
Uncaught ReferenceError: x$ is not defined
e.g. you want to delete the x in x$('body').addClass('home');

Javascript hiding and showing dynamic content of a div

Currently I hide and show the content of a div like this:
var header = null;
var content = null;
var mainHolder = null;
var expandCollapseBtn = null;
var heightValue = 0;
header = document.getElementById("header");
content = document.getElementById("content");
mainHolder = document.getElementById("mainHolder");
expandCollapseBtn = header.getElementsByTagName('img')[0];
heightValue = mainHolder.offsetHeight;
header.addEventListener('click', handleClick, false);
mainHolder.addEventListener('webkitTransitionEnd',transitionEndHandler,false);
function handleClick() {
if(expandCollapseBtn.src.search('collapse') !=-1)
{
mainHolder.style.height = "26px";
content.style.display = "none";
}
else
{
mainHolder.style.height = heightValue + "px";
}
}
function transitionEndHandler() {
if(expandCollapseBtn.src.search('collapse') !=-1)
{
expandCollapseBtn.src = "expand1.png";
}
else{
expandCollapseBtn.src = "collapse1.png";
content.style.display = "block";
}
}
This is fine if the content is static, but I'm trying to populate my div dynamically like so.
This is called from an iphone application and populates the div with a string.
var method;
function myFunc(str)
{
method = str;
alert(method);
document.getElementById('method').innerHTML = method;
}
I store the string globally in the variable method. The problem I am having is now when I try expand the div I have just collapsed there is nothing there. Is there some way that I could use the information stored in var to repopulate the div before expanding it again? I've tried inserting it like I do in the function but it doesn't work.
Does anyone have any ideas?
to replicate:
Here is the jsfiddle. jsfiddle.net/6a9B3 If you type in text between
here it will work fine. I'm not sure
how I can call myfunc with a string only once in this jsfiddle, but if
you can work out how to do that you will see it loads ok the first
time, but when you collapse the section and attempt to re open it, it
wont work.
If the only way to fix this is using jquery I dont mind going down that route.
is it working in other browsers?
can you jsfiddle.net for present functionality because it is hard to understand context of problem in such code-shoot...
there are tonns of suggestions :) but I have strong feeling that
document.getElementById('method')
returns wrong element or this element not placed inside mainHolder
update: after review sample in jsfiddle
feeling about wrong element was correct :) change 'method' to 'info'
document.getElementById('method') -> document.getElementById('info')
I think you want to use document.getElementById('content') instead of document.getElementById('method') in myFunc.
I really see nothing wrong with this code. However, a guess you could explore is altering the line
content.style.display = "none";
It might be the case that whatever is displaying your html ( a webview or the browser itself) might be wiping the content of the elemtns, as the display is set to none

Using script variables in html body

I want to call the variable from the script to body.
Here is my script code. I want to take the rightanswers and wronganswers values to use in html body.
GetFeedback = function (a) {
if (a == CorrectAnswer) {
rightanswers++;
} else {
wronganswers++;
}
lock = true;
}
You need to use the Document Object Modle. You have different methods with JavaScript to create and insert elements into the DOM. As for example:
var element = document.createElement('p');
var body = document.body;
body.appendChild(element);
With that code you are creating an element, then appendig it into the body. And that is pure JavaScript. You could use Mootools or jQuery, and It is goign to be simpler. But JavaScript doesn't work like PHP for example, where you can use the variables mixed up with the HTML.
And if you want to trigger the function from the HTML you need to bind thtat function to an event. For example clicking on a link would be.
HTML
Click Here
JS
var b = document.getElementById('button');
b.click = function(){
GetFeedback();
}
Make sure you're declaring the variable (we can't see that in the code provided) by using var:
<script>
var GetFeedback = function (a) {
if (a == CorrectAnswer) {
rightanswers++;
} else {
wronganswers++;
}
lock = true;
</script>
Then in your HTML, you can use feedback like this (although, it's not good practice to use the below, it's merely for demonstration purposes):
Hello
you can use jquery to change the html on the page.
GetFeedback = function(a){
if(a==CorrectAnswer){
rightanswers++;
}else{
wronganswers++;
}
lock=true;
$('p:first').html('Right Answers: '+rightanswers+' <br> Wrong Answers: '+wronganswers);
};
and have this as your html
<body>
<p></p>
Get Feedback
</body>

Categories