Find the DOM location of a function call - javascript

I know that in Jquery you can get the event.id if I had triggered an event (click, etc) but how would I get the DOM location of a simple function call
Ex :
<pre id="container2">...
<script>
FunctionCall();
</script>
</pre>
I would like to get the "container2" value from inside my FunctionCall

In general, the script does not know where it was launched from so there is no generic way to do what you were asking. You will have to either find a container div that you know in advance or insert your own known object that you can then find.
In your specific example, you could do this:
<pre id="container2">...
<script>
var fCntr = fCntr || 1;
document.write('<div id="FunctionCallLocation' + fCntr + '"></div>');
FunctionCall(fCntr++);
</script>
</pre>
Then, from within the script, you can find the DOM element with the id that was passed to it.
Or, you could put the document.write() into the function itself so it marks its own location:
var fCntr = 1;
function FunctionCall() {
var myLoc = "FunctionCallLocation" + fCntr++;
document.write('<div id="' + myLoc + '"></div>');
var myLoc = document.getElementById(myLoc);
}
This exact code would only work if FunctionCall was only called at page load time so the document.write() would work as desired.

Maybe you could try add an id or class to the script element. So something like this:
<pre id='container2'>
<script id='location'>
(function FunctionCall() {
var container2 = document.getElementById('location').parentNode;
container2.appendChild(document.createElement('p'));
}())
</script>
</pre>

Related

How to display result of javascript as HTML link?

I have the following code that I use to retrieve the hostname of a server and append some text (a filename) to it and display it on an html page.
<script type="text/javascript">
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
<script type="text/javascript">
document.write(getBaseUrl() + "filename.ext");
</script>
That generates a server URL such as https://fqdn/folder/filename.ext which is exactly what I need. Everything I have tried to create a link from it breaks things. How do I make that generated text clickable?
It's pretty straight forward to do -
const link = getBaseUrl()+ "filename.ext";
createLinkNode(link, document.body);
// defining a function to create a link node, however this isn't neccessary,
// you could just hard code the logic above.
// I wouldn't recommend setting innerHtml in lieu of making a text node however.
function createLinkNode(url, parent) {
const linkTextNode = document.createTextNode(url);
const linkNode = document.createElement('a');
linkNode.href = url;
linkNode.appendChild(linkTextNode);
parent.appendChild(linkNode);
}
example: https://jsfiddle.net/f4wxvLky/3/
You'd need to wrap it in an <a href=''></a>. This is easiest if you assign the <a> element in question to a variable, as you can then use .href to modify the link, along with .innerHTML to modify the text:
function getBaseUrl() {
return 'http://www.google.com/';
}
const output = document.getElementById('output');
output.innerHTML = 'Link Title';
output.href = getBaseUrl() + "filename.ext";
<a id="output" href=""></a>
If you don't have access to the HTML, this can still be done with raw JavaScript by simply including the <a href=''></a> wrapper in your output, being careful to also output the single quotes:
function getBaseUrl() {
return 'http://www.google.com/';
}
document.write("<a href='" + getBaseUrl() + "filename.ext" + "'>Link Title</a>");
Try this out, I assume getBaseUrl() is working although this doesn't look like. Just a reminder that <a> tag needs to be under the <script> block
<script>
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
Click

Display a div on pageload

I am passing div name in the query string from one html page and retrieving that div name on the other html page. Now I want to display that specific div on the page.My code is
function onLoad()
{
var divname=window.location.search.substring(1);
document.getElementById(divname).style.display="block"; //error is in this line
}
But I am getting an error as "object expected". please help me
The window.location.search property returns the part of the URL that follows the ? symbol, including the ? symbol.
So for example it might return ?paramname=paramvalue. When you call substring(1) on it you get paramname=paramvalue which is what gets passed to the document.getElementById function which obviously is wrong because such element does doesn't exist on your DOM.
You could use the following javascript function to read query string parameter values:
function onLoad() {
var divname = getParameterByName('divname');
document.getElementById(divname).style.display = 'block';
}
This assumes that you have a query string parameter name called divname:
?divname=some_div_name
Adjust the parameter passed to the getParameterByName function if your query string parameter is called differently.
You might also want to introduce error checking into your code to make it more robust:
function onLoad() {
var divname = getParameterByName('divname');
var divElement = document.getElementById(divname);
if (divElement != null) {
divElement.style.display = 'block';
} else {
alert('Unable to find an element with name = ' + divname);
}
}
What I am suggesting is place your js at the end of the html code (before </body> tag). Do not use a function.
<html>
...
...
...
<body>
...
...
...
<script>
var divname=window.location.search.substring(1);
document.getElementById(divname).style.display="block";
</script>
</body>
</html>
I have re-written my function and it is working, code is like this
function load()
{
var divname = window.location.search.substring(1);
var params=divname.split('=');
var i=1;
alert(params[i].substring(0));
document.getElementById(params[i].substring(0)).style.display='block';
}

Adding javascript variable to hyperlink within script

I have been trying to create a hyperlink using a variable defined earlier in the same function to append:
var NAMEVARIABLE = responseArray[i].Name;
var TITLE_Game = document.createElement("p");
TITLE_Game.className = "TITLE_Game";
TITLE_Game.innerHTML = "<a href='Game_NAMEVARIABLE.html'>Games</a>";
I have tried the following using the solution found here: Passing Javascript variable to <a href >
Games
But that didn't work. I then tried adding an ID:
<a id="link" href="Game_.html?propid=">Games</a>
And adding this to the script: document.links["link"].href += NAMEVARIABLE;
This didn't work either. These links are occuring within Isotope, which I've run into newbie-problems making sure my JSON data is loading before the script executes. That's all working now, but I'm not sure if the reason the above methods aren't working is because of a similar issue, or if they simply are not the proper way to go about this.
Any help is much appreciated. Thank you
first of all, try debug your variable :
var NAMEVARIABLE = responseArray[i].Name;
alert(NAMEVARIABLE);
is it returning the desired return value or not.
and then the second thing, in your first style of script, try this instead :
TITLE_Game.innerHTML = "<a href='Game_"+NAMEVARIABLE+".html'>Games</a>";
I assumed you have (static) html collection with game_[number_id].html format
and if it's so, you can try further with your second style of script, and change it to this :
Games
you need to learn further about javascript strings concatenation
Use string concatenation to build up your inner html string.
Example:
var nameVariable = 'Foo';
var innerHtmlText = nameVariable + 'bar';
$('#someElement').html(innerHtmlText);
The contents of someElement will then contain the text: 'Foobar';
You just need string concatenation. modify link's href onclick would be considered as spam in most modern browser.
<div id="result">
the result:
</div>
<script type="text/javascript">
var name = "foo_bar";
var url = "page.html?key=" + name; //or.. "page_" + name + ".html";
var link = 'link here';
$("#result").addClass("g_title");
$("#result").append(link);
</script>
This can be achieved by either (i.e. pure JS or jQuery) ways without much hassle. Suppose you have this <a> element with some href
<a id="Link" href="/collection/categories/">Games</a>
Pure JavaScript way:
window.onload = function() {
var link= document.getElementById('Link'),
url = link.href + responseArray[i].Name + '.html';
link.setAttribute('href', url);
}
Using Jquery:
$(function(){
var link= $('#Link'),
url = link.attr('href') + responseArray[i].Name + '.html';
link.attr('href', url);
});

Replacing function contents dynamically in JavaScript

How do you completely replace a function in JavaScript?
I got this code, but it doesn't work. The DOM gets updated, though. What's up with that?
<html>
<head>
<script id="myScript" type="text/javascript">
function someFunction() {
alert("Same old.");
}
</script>
</head>
<body>
<input type="button" onclick="someFunction();" value="A button." />
<script>
function replace() {
var oldFunctionString = someFunction.toString();
var oldContents = oldFunctionString.substring(oldFunctionString.indexOf("{") + 1, oldFunctionString.lastIndexOf("}") );
var newCode = "alert(New code!);";
var newFunctionString = "function someFunction(){"+newCode+"}";
var scriptTag = document.getElementById('myScript');
scriptTag.innerHTML = scriptTag.innerHTML.replace(oldFunctionString,newFunctionString);
}
replace();
</script>
</body>
</html>
JSfiddle here
Setting .innerHTML doesn't re-execute a script. If you really wanted to do that, you'd have to create a new script element and append it to the DOM, which then overwrites what the previous script has done (not possible in all cases, of course).
If you want to replace that function, just use
somefunction = function() {
alert(New code!); // syntax error, btw
};
Of course, to replace only parts of the code (not knowing all of it) you could try regex and co. Still just reassign the new function to the variable:
somefunction = eval("("
+ somefunction.toString().replace(/(alert\().*?(\);)/, "$1New code!$2")
+ ")");
It seems you are trying to work with strings, not the function itself. Just do this instead:
someFunction = function () { /* your function code here */ }

Inserting javascript global variable in <div> tag in HTML body

I have the following tag in HTML:
<div data-dojo-type="dojox.data.XmlStore"
data-dojo-props="url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'"
data-dojo-id="bookStore3"></div>
I have the values 6204 and 2 in a couple of global variables in the script section:
<html>
<head>
<script>
...
var newNeId = gup('neId');
var newNeGroupId = gup('neGroupId');
...
</script>
</head>
</html>
Is it possible to have these variables in the div tag in the HTML body? If so, how?
To clarify this a bit more, I need to have the URL in the tag something like this:
url: 'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/'+newNeGroupId+'/'+newNeId
I changed it according to your requirement:
<html>
<head>
<script type="text/javascript">
// example data
var newNeId = 10;
var newNeGroupId = 500;
window.onload = function(e){
var myDiv = document.getElementById("myDiv");
myDiv.setAttribute("data-dojo-props", "url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/" + newNeId + "/" + newNeGroupId + "', label:'text'");
}
</script>
</head>
<body>
<div id="myDiv" data-dojo-type="dojox.data.XmlStore"
data-dojo-props="url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'"
data-dojo-id="bookStore3"></div>
</body>
</html>​
You could add them to the <div> using the same datalist pattern (MDN docu) as Dojo:
<div id="savebox" data-newNeId="6204" data-newNeGroupId="2"></div>
These attributes are then accessible by the element.dataset.itemName.
var div = document.querySelector( '#savebox' );
// access
console.log( div.dataset.newNeId );
console.log( div.dataset.newNeGroupId );
As #EricFortis pointed out, the question remains, why you want to do this. This only makes sense, if you pass those values on from the server side.
Take one parent div then set its id and then you can rewrite whole div tag with attributes using innerHTML.
document.getElementById('id of parent div').innerHTml="<div data-dojo-type=/"dojox.data.XmlStore/"
data-dojo-props=/"url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'/"
data-dojo-id=/"bookStore3/"></div>";
you can append values you wants in innerhtml now.
here's simple native js code to do it
var body = document.getElementsByTagName('body')[0];
var myDiv = document.createElement('div');
myDiv.setAttribute('id', 'myDiv');
var text = 'newNeId: ' + newNeId +
'<br/> newNeGroupId: ' + newNeGroupId';
body.appendChild(myDiv);
document.getElementById('myDiv').innerHTML = text;

Categories

Resources