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";
}
Related
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);
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");
}
}
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');
All that I have read says to use the element.onclick property, but that doesn't seem to be working in my situation. I'm trying to parse the number: 629216818 and set it to a varialbe: fbid. This is a Greasemonkey script, so the HTML can't be edited directly. I'm no pro, so I may be just doing something stupid, but here is my HTML and Javascript:
<div id="petRightContainer">
<a title = "Pet trainer bonus: Your companion will level 5% faster." href="setup.php?type=companion>Random=8167343321487308">
<div class="petRight" style="background-image:url(/fb/res/gui4/companion/cu_sith.jpg)"></div>
</a>
<div class="petRightLevel">
Dog
</div>
etc.
<script type="text/javascript">
fbid = 0;
fbidRegex = /\d{3,}(?=&fromWall=1)/;
if ( document.getElementsByClassName("petRightLevel")[0]){
element = document.getElementsByClassName("petRightLevel")[0].firstChild;
codeStore = element.onclick;
fbid = fbidRegex.exec(codeStore);
document.write("it is working ");
}
document.write(fbid);
</script>
The problem is in this line:
element = document.getElementsByClassName("petRightLevel")[0].firstChild;
If you are using Firefox and other browsers which support document.getElementsByClassName and in your HTML, there are spaces between <div class="petRightLevel"> and
<a href="#" onClick= ...>
, the firstChild is actually a text node not the link. All you need to do is remove the spaces and/or line break in between the two elements.
If you are using IE, the problem is still at the same line of the javascript because IE doesn't support document.getElementsByClassName up until version 8.
Update: The following javascript code work for all the browsers I tested without touching HTML:
<script type="text/javascript">
fbid = 0;
fbidRegex = /\d{3,}(?=&fromWall=1)/;
var divs = document.getElementsByTagName("div");
var link = null;
for (var i=0;i<divs.length;i++)
{
if(divs[i].getAttribute("class") ==="petRightLevel")
{
link = divs[i].getElementsByTagName("a")[0];
break;
}
}
if (link){
codeStore = link.onclick;
fbid = fbidRegex.exec(codeStore);
document.write("it is working ");
}
document.write(fbid);
</script>
If you only need to get the anchors, it would be much simpler than this.
I think this might work for you.
<script type="text/javascript">
fbid = 0;
fbidRegex = /\d{3,}(?=&fromWall=1)/;
if(document.getElementsByClassName("petRightLevel")[0]){
element = document.getElementsByClassName("petRightLevel")[0].firstChild;
// callback function to execute when the element onclick event occurs.
codeStore = element.onclick = function(){
fbid = fbidRegex.exec(codeStore);
document.write("it is working ");
document.write(fbid);
}
}
</script>
I need to manipulate HTML code. Specifically, the user should be able to copy/paste the code to create an AddThis button in a textarea, and I want to manipulate the pasted code.
A typical AddThis button looks like this :
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_counter addthis_pill_style"></a>
</div>
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-123456798"></script>
<!-- AddThis Button END -->
It consists of start and end comments, a div and/or some links, followed by 2 scripts: a config setting, and a call to their library.
The problem is, we need to call this many times on the page ; so, if I just put this every time I want to place an AddThis button, I fear that at least some browsers will have weird behavior, if it works at all.
So, I want to extract the config setting and the lib call, so I can call them just once, and extract the buttons config, so I can place it as many times as I want on the page.
I have already done that :
var codeAT = $(this).val();
if (codeAT.indexOf("AddThis Button BEGIN") >= 0) {
codeAT = codeAT.replace("<", "<");
codeAT = codeAT.replace(">", ">");
codeAT = $(codeAT);
// extract the call to the config var and the lib
var scriptConfig = "";
var scriptSRC = "";
codeAT.each(function() {
if ($(this).attr("nodeName") == "SCRIPT") {
if ($(this).attr("src") && $(this).attr("src") != "") {
scriptSRC = $(this).attr("src");
} else {
scriptConfig = $(this).text();
}
}
});
// extract the addthis identifier
scriptSRC = scriptSRC.split("=")[1];
}
Now, I can use the vars scriptConfig (with var addthis_config = {"data_track_clickback":true};) and scriptSRC (with ra-123456789), and they have the correct values.
What I want now, is the original code (between the two comments), without the comments, and without the script tags.
To remove the tags, I tried to use codeAT.remove($(this)), but it crashes (something about c.replace not being a function).
To get the code back, I tried codeAT.html(), but it gets only the tags.
Instead of .each() I'd do:
//remove <script> tags and get required info
var scriptSRC = $('script[src]', codeAT).remove().attr('src');
var scriptConfig = $('script:not([src])', codeAT).remove().text();
//get the code (as string)
var code = $('<div>').append(codeAT).remove().html();