I am trying to insert some new links using ‘innerHTML’. As there may be a number of calls on the same ‘ids’ I thought it would be wise to use variables. The following does not respond beyond the alert? The process works fine if I don’t use ‘var link’ and just enter it in full. Is there an issue perhaps trying to do this with xhtml?
Thanks.
var newlink = '<a title="new link" href="newlink.htm">New Link</a>';
var link = "document.getElementById('idlink')";
if( link ) {
alert("link confirmed");
link.innerHTML = newlink;
}
var link = "document.getElementById('idlink')";
should be
var link = document.getElementById('idlink');
You are assigning a string to the variable. Just because the contents of the string looks like code that could be run doesn't mean that it actually runs. It's just a string.
Call the method and assign the result to the variable:
var link = document.getElementById('idlink');
Related
This is my first experience with JS, so please forgive the noob question.
I'm trying to make a userscript for a phpBB forum that'll allow me to automatically bookmark every topic I create.
My approach is to add an onclick listener to the submit button.
I'll use the code found in another question:
var submit = document.getElementsByTagName('input')[0];
submit.onclick = function() {
;
}
Before that though I want to find a link to bookmarking the topic in one of the hrefs on the page and store it as a variable.
I know that it will always take the form of
<a href="./viewtopic.php?f=FORUM_NUMBER&t=TOPIC_NUMBER&bookmark=1&hash=HASH"
The final code should look something like (hopefully it's the correct form)
var link = THE LINK EXTRACTED FROM THE MATCHED HREF
var submit = document.getElementsByTagName('input')[0];
submit.onclick = function() {
setTimeout(function(){ window.location.href = 'link'; }, 1000);
}
My issue is I don't know how to approach locating the href that I need and getting the link from it. Haven't found any similar questions about this.
Thanks in advance for any help
Maybe something like this?
var anchors = document.getElementsByTagName('a'); // get all <a> tags
var link = '';
if (anchors) {
// getAttribute(attributeName) gets the value of attributeName (in your case, the value of 'href' attribute
// .map(), .find() and .filter() are available methods for arrays in JS
// .startsWith() is an available method for matching strings in JS.
// You can even experiment with other regex-based string matching methods like .match()
// Use one of the following lines, based on what you require:
// to get the first matching href value
link = anchors.map(anchor => anchor.getAttribute('href')).find(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
// to get all matching href values as an array
link = anchors.map(anchor => anchor.getAttribute('href')).filter(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
}
Since you're not new to coding, check out this documentation if you're new to JS :)
Happy coding!
You can try document.getElementsByTagName("a"); which returns a collection of all the <a></a> loaded in the dom.
Then you can find it in the list and and use .href to get it's href attribute.
Trying to open a picture in a new tab, the values comes from a looping object.
How will I pass the value of doc.strDocument to onClick ?
PUG:
a(onClick="window.open('/userImages/documents/'+doc.strDocument);")
HTML:
<a onClick="window.open('/userImages/documents/'+doc.strDocument);"></a>
Your concatenation is fine (as long as strDocument has a value that when concatenated with the static text forms a valid URL).
But, this is much simpler when it comes to <a> elements - no onclick needed because <a> elements can target new windows with the target attribute.
function getLink(){
var someData = "foo";
return "some/path/" + someData;
console.log(link.href);
}
test
And, even that should be improved by moving the JavaScript out from being inline with the HTML:
var someDynamicallyGottenValue = "foo";
var link = document.getElementById("dynamicLink");
link.href = 'http://someDomain.com/' + someDynamicallyGottenValue;
console.log(link.href);
test
You can pass JSON data to Pug.
{"book": {"name": "Dracula"}}
And your PUG code would be,
a(onClick="window.open('/userImages/documents/#{book.name}');")
Pug also support variables.
- var foo = book.name;
a(onClick="window.open('/userImages/documents/#{foo}');")
Tested using - http://naltatis.github.io/jade-syntax-docs/#variables
Hope this helps.
I have a button that runs a batch file, which the code is:
<button onclick="window.open('file:///C:/Users/gthornbu/Desktop/TEST/test.bat')">Continue</button>
I can put that directly in the HTML file and it works just fine, however I am inserting this specific piece of code into the file via output.innerHTML and it's not working. I assume the "/" have to be changed, but I have also tried:
<button onclick='window.open('file:///C:\\Users\\gthornbu\\Desktop\\TEST\\test.bat')'>Continue</button>...which also does not work. Any ideas what I'm missing here?
JavaScript I am using:
function novpn() {
var output = document.getElementById("main");
var sentence = "<h3>You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.</h3></br><button onclick='window.open('file:///C:\\Users\\gthornbu\\Desktop\\TEST\\test.bat')'>Continue</button>";
output.innerHTML = sentence;
}
You have ' nested within '.
The easy way out is to use ", but escaped, as the inner quote. Then go back to the original URL (with forward slashes):
var sentence = "<h3>You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.</h3></br>" +
"<button onclick='window.open(\"file:///C:/Users/gthornbu/Desktop/TEST/test.bat\")'>Continue</button>";
You can declare strings with ", ' characters. If you have to call a function with parameter in html attribute, declaration may become a problem.
You can resolve this with escape character. \
It will escape behaving the character caused. You must add before it.
var str = "string";
var str2 = \""string\"";
str === str2 // true
In your case, you can do it like this.
output.innerHTML = '<button onclick="window.open(\'file:///C:/Users/gthornbu/Desktop/TEST/test.bat\')">Continue</button>'
Working JS Fiddle
http://jsfiddle.net/ebilgin/wLe04pwg/
Nesting html markup and javascript code in strings can become an headache to get the single and double quotes right and escaped where needed. Although it allows for some rather rapid application development if you need to maintain this later you might give this solution try.
Instead of figuring out which quote needed to go where I recreated your target html in vanilla javascript commands to create the same result by using different functions and wiring it all together.
I used the document.createElement function to create the html elements needed and the appendChild function to add them to the main element. The button get the function for opening the window attached to the onclick event.
function novpn() {
var output = document.getElementById("main");
// create the h3 elelement and its content
var h3 = document.createElement('h3');
h3.innerHTML = "You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.";
// the br
var br = document.createElement('br');
// create the button
var button = document.createElement('button');
button.innerHTML = "Continue";
// the onclick handler can now become
// a normal javascript function
button.onclick = function() {
window.open('file:///C:/Users/gthornbu/Desktop/TEST/test.bat');
};
// add all created elements to main
output.appendChild(h3);
output.appendChild(br);
output.appendChild(button);
}
// start
novpn();
<div id='main'>
<div>title</div>
</div>
I am new to javascript. I am trying to append a variable to a link like this. I am able to get the var name but it's not working when I append. i tried couple of other things. Any suggestions for appending the variable name.
<script type="text/javascript">
var name = document.getElementById('name').value;
window.location.href = "http://example.com?id=5678&name=+name+&code=1234
</script>
Simply end and restart the quotes like so
window.location.href = "http://example.com?id=5678&name="+name+"&code=1234";
You can imitate sprintf function by:
window.location.href =
"http://example.com?id=5678&name=%name&code=%code"
.replace('%name', 'myName')
.replace('%code', '123456');
I am tring to add some content after the original content, but the new content will cover the original content everytime...What wrong in this case? (Sorry for my terrible english...)
var originaltext = document.getElementById("id").innerHTML;
document.getElementById("id").innerHTML = originaltext + "newtext";
One more thing,I tried to use alert to show the "originalltext", but it have nothing to show.
alert(originaltext);
your code looks ok to me. I made a jsfiddle for you just to see that it works http://jsfiddle.net/3mqsLweo/
var myElement = document.getElementById('test');
var originalText = myElement.innerHTML.toString();
myElement.innerHTML = originalText+" new text";
check that you only have one element with the id "cartzone"
A simple and fast way to do this is to concatenate the old value with the new.
document.getElementById('myid').innerHTML += " my new text here"
this problem usually occurs when the rest of your code is poorly written and contains errors or when the same ID is used several times.
I had the same problems in the past.
you have tow options:
check the rest of your code (validate)
use jQuery - I don't know how, but it works every time.