HTML section identified by URL segment not found within webpage - javascript

How can I notify the user when the section identified by the url fragment is not found on a webpage?
Example:
website1 contains:
bring me to the foo section of website2
and website 2 contains:
<div id="foo"> I'm the foo section </div>
So if I click the link and the identifier of the div is not "foo" but "bar" the webpage displays an alert like "foo section not found".
Context: I'm exposing on an html page a JSON response for an API and I want the attributes of the JSON to link to a documentation page. If the section describing that attribute is not found an alert should suggest to update the documentation.
UPDATE: without using javascript frameworks if possible
Thanks

This should do the trick.
On "onLoad" of website2 I check if the url contains a segment and then look for that Id in the document using getElementById(segment) ..
<html>
<body onload="myFunction()">
<h1>Hello World!</h1>
<script>
function myFunction() {
var segment;
if(window.location.hash){
segment = window.location.hash.substring(1);
if( document.getElementById(segment) == null ){
alert("html element with id "+segment+" not found");
}
}
}
</script>
</body>
</html>

Are you using jQuery?
You can't do this with html or css, but you can do it very easily with jQuery, like this:
$('.navigation a').on("click", function(){
//This gets the href and splits it on "#". Grabs the value after "#"
//Make sure to only have 1 # in a link
var idToFind = $(this).attr("href").split("#")[1];
//Check if a div with this ID exists
if($('#'+idToFind).length > 0){
//it has been found, you could turn the scrolling to the section into a neat animation here, if you want
}
else{
//It has not found it. Alert.
alert('"' + idToFind + '" section not found');
}
});
edit
Here's a vanilla js solution:
html:
bring me to the foo section
Javascript:
function checkSection(section){
var idToFind = $(this).getAttribute("href").split("#")[1];
//Get the element
var element = document.getElementById(idToFind);
//check if element exists
if (typeof(element) != 'undefined' && element != null)
{
// exists.
}
else{
//doesn't exist
alert(idToFind + "doesn't exist");
}
}

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);

Search for Text in Loaded HTML document

I have a web page on which my sidebar links will cause an 'external' HTML document to be loaded into a content div.
However after it is successfully loaded and displayed, the loaded HTML content does not appear in the Page Source.
Regardless, I now need to do a client-side Text Search of that 'external' HTML document using a Javascript function.
My webpage looks like the following:
The Search textbox and button are 'outside' of the Content Div (bordered in Red).
And, at the time that one of the link's HTML documents is appearing on-screen the page source looks like:
<!-- Page Content -->
<div id="page-content-wrapper" style="border: thick solid #FF0000; height:660px">
<!--Loaded content goes here-->
</div>
Notice that the 'loaded' HTML document is not showing.
I have found a Javascript function findInPage() which looks promising, but it is not finding the 'loaded' HTML document and its text.
// =====================================
function findInPage() {
var str = document.getElementById("ButtonForm").elements["txtSearch"].value;
var n = 0;
var txt, i, found;
if (str == "")
return false;
// Find next occurance of the given string on the page, wrap around to the
// start of the page if necessary.
if (window.find) {
// Look for match starting at the current point. If not found, rewind
// back to the first match.
if (!window.find(str)) {
while (window.find(str, false, true))
n++;
} else {
n++;
}
// If not found in either direction, give message.
if (n == 0)
alert("Not found.");
} else if (window.document.body.createTextRange) {
txt = window.document.body.createTextRange();
// Find the nth match from the top of the page.
found = true;
i = 0;
while (found === true && i <= n) {
found = txt.findText(str);
if (found) {
txt.moveStart("character", 1);
txt.moveEnd("textedit");
}
i++;
}
// If found, mark it and scroll it into view.
if (found) {
txt.moveStart("character", -1);
txt.findText(str);
txt.select();
txt.scrollIntoView();
n++;
} else {
// Otherwise, start over at the top of the page and find first match.
if (n > 0) {
n = 0;
findInPage(str);
}
// Not found anywhere, give message. else
alert("Not found.");
}
}
return false;
}
Is there some way to modify the function and/or use a different function such that it can find the 'loaded' HTML document and search it for the entered Text?
try selecting the div by id instead of reading the whole window...
document.getElementById('page-content-wrapper').find(str)
This is a duplicate of How to get html elements from an object tag?.
The answer lies in replacing all instances of window.document with document.getElementById('page-content-wrapper').contentDocument, such that the searched document is the page document.
However, the search function you have there is quite broken, it depends on window.find to search the window instead of searching the document text.
You could build a better search function:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Wrapper</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
Body Here
<object id="page-content-wrapper" type="text/html" data="about.html" name="content"></object>
<input id="txtSearch" placeholder="Search..." />
<button onclick="findInPage()">Search</button>
<script>
function findInPage() {
var needle = document.getElementById('txtSearch').value;
var haystack = document.getElementById('page-content-wrapper').contentDocument.body.innerHTML;
var match = haystack.indexOf(needle);
if(match != -1) {
console.log(match);
} else {
console.log('Not Found');
}
}
</script>
</body>
</html>
Fill about.html with anything you want to load and search in.
Note that this just logs the index of the match. It doesn't scroll it into view or select it. With a little more javascript you can do those though. You just have to go through document.getElementById('page-content-wrapper').contentDocument.body
I finally found how to access the HTML content of the Object's innerHTML.
Upon clicking on a specific Sidebar link, using Javascript, I build its Object.
function MenuClick(doc) {
var Tutorial = doc;
var DisplayObj = "<object id='ThisObj' type='text/html' data='" + Tutorial + "' style='min-width:100%; min-height: 101%; overflow: hidden'></object>";
document.getElementById("page-content-wrapper").innerHTML = DisplayObj;
}
But now I have added an ID to the Object ('ThisObj').
With that ID now defined I was able to 'drill-down' into that Object to get to its innerHTML.
var sourceObj = document.querySelector("#ThisObj");
var sourceBody = sourceObj.contentDocument.body
var haystack = sourceBody.innerHTML;
var match = haystack.indexOf(needle);
if (match != -1) {
// --- Text match found ---
} else {
// --- Text match NOT found ---
}
I still need to create the Javascript to highlight the 'found' text and scroll it into view but I'll ask that question in a separate post.
Thanks for your suggestions/advice.

javascript that is supposed to show/hide text according to url is not working

This code is supposed to show/hide a text based on the page's url, but it's not working:
var pages = window.location.href;
if(pages == "page1.html"){
//display page 1 text
}
else if(pages == "page2.html"){
//display page 2 text
}
http://jsfiddle.net/yp8h2moe/1/
I tested it localy, didn't work, so I tested with jsfiddle, but unfortunately every time you save a jsfiddle, you get a new url.
UPDATE
Here is the updated code, I was able to run it specifying the file extention, but I need it to run with the url only:
<script>
var pages = window.location.href;
if( pages.split('/').pop() === 'http://akecheta.com/free-blogger-templates/' ) {
document.write('<b>Hello World 1</b>');
}
else if( pages.split('/').pop() === 'http://akecheta.com/free-blogger-templates/' ) {
document.write('<b>Hello World 2</b>');
}
</script>
THE SOLUTION
How can I insert HTML text in Javascript the right way?
The value of href is usually an absolute URL so you have to use .indexOf() as follows:
var pages = window.location.href;
if(pages.indexOf("page1.html") > -1){
//display page 1 text
}
else if(pages.indexOf("page2.html") > -1 ){
//display page 2 text
}
Alternatively you could use .split() and .pop(), assuming your urls do not have query strings:
if( pages.split('/').pop() === 'page1.html' ) {
//...
UPDATE
When using absolute URLs or larger parts thereof, you do not need to use .split() and .pop(). Bear in mind that split creates an array whereas pop obtains the last element of that array. You won't be needing this process with absolute URLs.
var pages = window.location.href;
if( pages.indexOf( 'http://akecheta.com/free-blogger-templates/' ) > -1 ) {
document.write('<b>Hello World 1</b>');
}
else if( pages.indexOf( 'http://akecheta.com/free-blogger-templates/xx' ) > -1 ) {
document.write('<b>Hello World 2</b>');
}
It doesn't work because in your jsfiddle var pages is "http://fiddle.jshell.net/_display/ "
try to console.log it and make sure to trim it too if it is needed..
In your case for page1.html etc.. you have to compare it to the full/absolute path
If your URL is http://wwww.example.com/page1.html, then you need the URL path. So, code will look something like below
var pages = location.pathname;
if(pages == "/page1.html"){
//display page 1 text
}
else if(pages == "/page2.html"){
//display page 2 text
}

Hiding Content Based on Content of URL String

I am trying to hide a certain fieldset with an id of "retail" based on if the URL has 'studio' as a part of it. The URL would read as follows:
/island-careers/studio/accounting/accountant/apply.html
Here is my script I have written up but I can't seem to get it to recognize if 'studio' is in the URL.
<script>
jQuery(document).ready(function(){
var path = window.location.pathname;
console.log(path);
var split = window.location.href.split('/');
console.log(split);
console.log(split[4]);
if (split[4] === 'studio') {
jQuery('#retail').css('display, none');
}
});
</script>
The "console.log(split[4]); was to find the location of 'studio' in the array. There must be something wrong with my IF statement I guess. I also tried this method but it didn't work for me either:
<script>
jQuery(document).ready(function(){
var path = window.location.pathname;
console.log(path);
if (path.indexOf('studio') >= 0) {
jQuery('#retail').css('display, none')
}
});
</script>
Your jQuery line to change the CSS should be:
jQuery('#retail').css('display', 'none');

Using an if statment with a partial address to adress a link

Trying to figure out a way to use Javascript to set up a little if-else statement using only part of the url to determine if a link should go one place or another. So far what I got is,
<script type="text/javascript">
if (url.indexOf("example.com/") != -1)
{
Blahblah
} else {
Blahblah
}
</script>
The problem is that the link doesn't even appear so I don't know how wrong or not I am.
Thanks for any help.
Edit: Lets just say for the sake of argument it is a blank html page. As in <html>
<body>
</body>
</html>
Looking for more of a proof of concept then branch out into getting this working on a full scale site.
Edit #2:
Figured it out, even has url detection.
<a id="link">link</a>
<script type="text/javascript">
var link = document.getElementById('link');
var referrerUrl = document.referrer;
if (referrerUrl.indexOf("searchurlfor") != -1)
{
link.href = "place1";
} else {
link.href = "place2";
}
</script>
Try not mixing HTML and JavaScript:
<a id="someLink" target="_blank">Blahblah</a>
<script>
document.getElementById('someLink').href =
(url.indexOf("example.com/") != -1)? 'placeone.htm' : 'placetwo.htm'
</script>
or more verbosely:
<script>
var linkElem = document.getElementById('someLink');
if(url.indexOf("example.com/") != -1) {
linkElem.href = 'placeone.htm';
} else {
linkElem.href = 'placetwo.htm';
}
</script>
Preferably the script should go to a separate file. The way you suggest feels like PHP or JSP but JavaScript does not work this way. In the example above you first render empty link and change the href attribute afterwards.
I think you want:
<script>
if (url.indexOf("example.com/") != -1)
{
document.write('Blahblah');
} else {
document.write('Blahblah');
}
</script>
You need getElementById
HTML:
<a id="link">link</a>
Javascript
<script type="text/javascript">
var link = document.getElementById('link');
if (url.indexOf("example.com/") != -1)
{
link.href="placeone.com";
} else {
link.href="placetwo.com";
}
</script>
You'd have to show us where/when this code is executing in your page. You can't just drop HTML into the middle of a piece of javascript like you were doing.
You can call:
document.write('Blahblah');
to insert HTML into the current place in the document if this is an inline script.
If this code is not executing inline in the document, then you should not use document.write() as that will clear your document and start a new one. Instead, you would use DOM manipulation functions to insert this into the appropriate place in the page or to change the href on an existing link. For example to change the href on an existing link when you have this HTML:
<a id="myLink" href="placeone.com" target="_blank">Blahblah</a>
You would use this javascript that must run after the page has been loaded:
var link = document.getElementById("myLink");
(url.indexOf("example.com/") != -1) {
link.href = "placeone.com";
} else {
link.href = "placetwo.com";
}

Categories