create link in javascript function with --- innerHTML = "...<a href='http://...'>HttpLink</a>..." - javascript

I'm learning to write with html, but I have one problem I cannot understand.
The following code works in other browsers but not in IE9. I know it has something to do with innerHTML but I could not understand the answers I found for this.
<html> <head> <script type="text/javascript">
function hw_function1() {
var img11=document.createElement("a");
img11.innerHTML = "<html> <body> <a href='http://google.de'>Google</a> </body></html>";
document.body.appendChild( img11 );
}
</script>
<body>
<a href="#" onclick="javascript:hw_function1()";>Test</a>
</body> </html>
What should I change WITHOUT changing the structure (only the innerHTMl-part if possible)?

Since you're creating an a element, you simply assign the href to the element via the .href property.
You can set its text content with .innerHTML as a convenience, though it's not really a "pure" approach.
var img11=document.createElement("a");
img11.href='http://google.de';
img11.innerHTML = 'Google';
document.body.appendChild( img11 );
Another way to set the text content would be like this...
img11.appendChild(document.createTextNode("Google"));

You code is creating another HTML page inside the original. That is wrong and invalid. It's because some browsers are forgiving and correcting things that your code even works.
If you're creating a hyperlink element, you should be adding text or an image or other inline elements inside it using innerHTML.
You should change its attribute to set the href with img11.href='http://xyz.com';

Related

Javascript changing innerHTML to a different pages content not working [duplicate]

This question already has answers here:
Replace innerhtml with external page
(2 answers)
Closed 7 years ago.
EDIT SOLVED:
Below works great. The suggested link marking this a duplicate does not solve the problem.
changeDrinks.innerHTML = '< object type="text/html" data="drinks.html" > </object > ";
What is wrong with my javascript below?
JS :
var changeDrinks = document.querySelector("#menuDropWine");
changeDrinks.innerHTML = 'drinks.html';
I wanted this to change the content of a div to drinks.html webpage. The div's content that is being changed looks like this...
<div id="menuDropWine" class="divBtn">
I've read a couple questions on here already about changing the content of a div. Some used ajax, others used jQuery, but I feel I should be able to just use innerHTML equals a link. Currently this is just changing my div's content to the literal text output of 'drinks.html'. I hope I'm just missing an a href reference or something, as I feel this solution should be simple. The only real reason I want to put this into my website is so it cleans the looks of my index.html to not have so much text content, by storing the text content in different links that just load on a click.
Thanks for your time.
You are misunderstanding the function of innerHTML; it accepts a string of HTML, creates the required DOM structure and injects it into the the target element. The easiest way to achieve what you want is with an iframe, setting its src property to 'drinks.html'.
<iframe src="drinks.html" frameborder="0">Your browser doesn't support iframes</iframe>
Assuming that drinks.html is a full HTML document (has an <html>, <head> and <body> tag), this is really the best route. If drinks.html is a partial HTML document then you could look into using AJAX. I would suggest using jQuery and then you could easily do something like:
$('#menuDropWine').load('drinks.html');
The short answer to your question is that the element will be filled with the text drinks.html, which is not incorrect, but obviously not what you had in mind.
JavaScript is not psychic, so it doesn’t know whether you want to change the content or load from an external document, so this behaviour is perfectly natural.
If you want a simple solution, use an iframe, whose src attribute can be set in JavaScript as follows:
var changeDrinks = document.getElementById("menuDropWine");
changeDrinks.src = 'drinks.html';
BTW note that if you know you are using an id, it is more efficient to use document.getElementById.
If you really want to use innerHTML, as the others have commented, you will have to use Ajax. A simple example, without jQuery, follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<script type="text/javascript">
window.onload=init;
function init() {
var test=document.getElementById('test');
var url='test.html';
load(test,url);
}
function load(element,url) {
var xhr=new XMLHttpRequest();
xhr.open('get', url, true);
xhr.send(null);
xhr.onreadystatechange=function() {
if (this.readyState==4) {
element.innerHTML=this.responseText;
}
}
}
</script>
</head>
<body>
<h1>Test</h1>
<div id="test">Hello</div>
</body>
</html>
Here, test.html is expected to have your new content.

How or can I use JavaScript to append a div tag after the html or body tags?

For a very specific reason I would like to know if you can add a tag either after the body or html tags.
<!DOCTYPE html>
<html>
<body>
</body>
<!-- Can I add a tag here? -->
</html>
<!-- Can I add a tag here? -->
I have noticed this is what the Skype plugin for Chrome does, and would like to know how they did it. I have attached a screenshot of proof.
You can append some element after the body element as such:
var e = document.createElement('a');
document.body.parentNode.appendChild(e);
Attempting to insert an element which is a sibling of the html element results in the following error:
There are several ways to do it, KPthunder's sample springing to mind. You can also just rewrite the content of the entire document and reload it. Ugly, and brutal, but it works.
Note, however, that browsers are not required to honor the element. As mentioned, it's noncompliant, and therefore not guaranteed to work across all browsers. It'll likely work in IE. But that's IE. And IE supports everything. </eyeroll>
I've actually encountered elements that appeared both before and after the HTML element itself, and it wasn't intentional (cough). Likely, this is the case here. My advice to you is, don't try to repeat it.
Sorry for jQuery but, for example
$( "<p>Test</p>" ).insertAfter( "body" );

.InnerHTML Not working properly in Internet Explorer

I wanted to assign a link tag to innerHTML of a HTML control. But this is not working properly in Internet Explorer. However when I try to assign anything other than <link> & <style> tags it works fine.
<html>
<head>
<script type="text/javascript">
function getValue()
{
var x=document.getElementById("myHeader");
x.innerHTML='<link \"http://test.com/css/template.css\" rel=\"stylesheet\"><div>abc</div>';
alert(x.innerHTML);
}
</script>
</head>
<body>
<h1 id="myHeader" onclick="getValue()">Click me!</h1>
</body>
</html>
Also, If I change sequence of <div> tag and <link> tag above it works fine in Internet Explorer also.
x.innerHTML='<div>abc</div><link \"http://test.com/css/template.css\" rel=\"stylesheet\">';
Please suggest! Thanks.
EDIT: This is a bug in Internet Explorer with ExtJs. More information at
http://www.sencha.com/forum/showthread.php?30110-internet-explorer-autoLoad-css-not-applied
innerHTML won't work in IE, but using DOM methods it will:
function getValue()
{
var x=document.getElementById("myHeader")
, link = document.createElement('link')
, div = document.createElement('div');
x.innerHTML = '';
x.appendChild(link);
x.appendChild(div);
div.innerHTML = 'abc';
link.href = 'http://test.com/css/template.css';
link.rel = 'stylesheet';
alert(x.innerHTML);
}
Although the reference states a link tag may only appear in the header, interesting enough the style link does work if you use the code I provided, in all browsers I tried (IE, firefox, chrome). See this jsfiddle (where I used a real css-href from test.com ;-)
If you however want to place the link in it's rightful section (<head>), use:
var header = document.getElementsByTagName('head')[0];
, link = document.createElement('link');
header.appendChild(link);
link.href = 'http://test.com/css/template.css';
link.rel = 'stylesheet';
For starters, you are missing an href attribute on your <link>.
<link href=\"http://test.com/css/template.css\" rel=\"stylesheet\" />
And don't put link and style tags into the <body>. Inject them into the <head>
var link = document.createElement("link");
link.href = "http://test.com/css/template.css";
link.rel = "StyleSheet";
document.head.appendChild(link);
A lot of people are missing the point here. What he is trying to do ( after fixing the typo where the href attribute is missing ) works in any other browser.
IE 8 and below have a bug where if the first element in the text when setting innerHTML is a tag (maybe others), it is ignored. If you just put a space or newline or other tag first, it works.
He even discovered this when he said putting the <div> first fixes it.
It isn't valid, but that's how you fix it.
Edit: in other words: foo.innerHTML = "\n" + yourHtmlWithLinkInIt;
<link> can only be contained in <head>.
This element defines a link. Unlike A,
it may only appear in the HEAD section
of a document, although it may appear
any number of times.
reference: http://www.w3.org/TR/html401/struct/links.html#edef-LINK
i think the problem is that the <link> hast to be an empty element. change your code to this:
x.innerHTML='<link \"http://test.com/css/template.css\" rel=\"stylesheet\" /><div>abc</div>';
// this is the trick ^^^
EDIT: i havn't tested this, but it's the first thing that hurts my eyes.
EDIT2: <link> tags should only occur inside of the <head>-section... i hope you know what you're trying to do.
to the set text properly, i would recommend you to go what i generally do. if you have ie 8 then open the html in ie. press f12 to show the developer tool. now in the new window go to script tag. set break point from where your javascript starts. now press on the button start debugging. execute the js function from your by some event or the way it executes. now on the object in the javascripg function, when the break point hits, right click and add watch. expand the object and see, where your earlier text was and where is your new text.
What exactly are you trying to achieve, as your end goal? As said previously a link tag should really only appear in the <head> of an html document.
JavaScript can be a tricky thing in its vanilla flavour, you're better off using a framework, my personal favourite is MooTools though I hear JQuery is pretty good, but MooTools has OOP (for real programmers - tehe).
This'll allow you to do a lot more, and probably get to your end goal, if you let me / us know then you should get a more direct answer to your issue.
The thing is it works in FireFox and Google Chrome, but not in IE.
This is, because you cannot set the innerHTML tag of InternetExplorer with a string, if the string is more than text, ie a HTML element.
I experienced this trying to dynamically populate a ComboBox into a table cell with AJAX...
The solution is to use JQuery.
Then you can do:
$("#YourElementID").html('<link \"http://test.com/css/template.css\" rel=\"stylesheet\" /> <div>abc</div>');
and JQuery will do the DOM stuff, that selbie and KooiInc describe, for you.
Found different and easy solution here for "link" and "sytle", but "script" needs to be added using appendChild. Very much similar to what Vectorjohn has said, also provides more references.
http://allofetechnical.wordpress.com/2010/05/21/ies-innerhtml-method-with-script-and-style-tags/
try
document.getElementById('tblList').outerHTML="ypur html";

What does innerHTML do in javascript?

Can anyone tell me what innerHTML does in javascript and give me example how I can use it?
The innerHTML property is used to get or set the HTML content of an element node.
Example: http://jsfiddle.net/mQMVc/
// get the element with the "someElement" id, and give it new content
document.getElementById('someElement').innerHTML = "<p>new content</p>";
// retrieve the content from an element
var content = document.getElementById('someElement').innerHTML;
alert( content );
The innerHTML property is part of the Document Object Model (DOM) that allows Javascript code to manipulate a website being displayed. Specifically, it allows reading and replacing everything within a given DOM element (HTML tag).
However, DOM manipulations using innerHTML are slower and more failure-prone than manipulations based on individual DOM objects.
innerHTML is a property of every element. It tells you what is between the starting and ending tags of the element, and it also let you sets the content of the element.
property describes an aspect of an object. It is something an object has as opposed to something an object does.
<p id="myParagraph">
This is my paragraph.
</p>
You can select the paragraph and then change the value of it's innerHTML with the following command:
document.getElementById("myParagraph").innerHTML = "This is my paragraph";
For understanding innerHTML property you first need to go through the basics of the javascript object and HTML DOM(Document object model). I will try to explain:
JavaScript objects consist of properties and methods.
for rendering HTML document web browser creates a DOM, in DOM every HTML element is treated as a JavaScript Object which has a set of properties and methods associated with it.
Now coming to your Question:
HTML code:
<p id= "myPara"> We love to Code.</p>
JavaScript code:
alert(document.getElementById("myPara").innerHTML);
here, document.getElementById("myPara") will return our html element as a javascript object which has pre-defined property innerHTML.
innerHTML property contains the content of HTML tag.
Hope this will help.
You can run following HTML code in your browser to understand it:
<html>
<body>
<p id= "myPara"> We love to Code.</p>
<script>
alert(document.getElementById("myPara").innerHTML);
</script>
</body>
</html>
Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages.
However, using innerHTML requires some preparation if you want to be able to use it easily and reliably. First, you must give the element you wish to change an id. With that id in place you will be able to use the getElementById function, which works on all browsers.
You can collect or set the content of a selected tag.
As a Pseudo idea, its similar to having many boxes within a room and imply the idea 'everything within that box'
The innerHTML fetches content depending on the id/name and replaces them.
<!DOCTYPE html>
<html>
<head>
<title>Learn JavaScript</title>
</head>
<body>
<button type = "button"
onclick="document.getElementById('demo').innerHTML = Date()"> <!--fetches the content with id demo and changes the innerHTML content to Date()-->
Click for date
</button>
<h3 id = 'demo'>Before Button is clicked this content will be Displayed the inner content of h3 tag with id demo and once you click the button this will be replaced by the Date() ,which prints the current date and time </h3>
</body>
</html>
When you click the button,the content in h3 will be replaced by innerHTML assignent i.e Date() .
innerHTML explanation with example:
The innerHTML manipulates the HTML content of an element(get or set). In the example below if you click on the Change Content link it's value will be updated by using innerHTML property of anchor link Change Content
Example:
<a id="example" onclick='testFunction()'>Change Content</a>
<script>
function testFunction(){
// change the content using innerHTML
document.getElementById("example").innerHTML = "This is dummy content";
// get the content using innerHTML
alert(document.getElementById("example").innerHTML)
}
</script>
Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages.
However, using innerHTML requires some preparation if you want to be able to use it easily and reliably. First, you must give the element you wish to change an id. With that id in place you will be able to use the getElementById function, which works on all browsers.
After you have that set up you can now manipulate the text of an element. To start off, let's try changing the text inside a bold tag.
JavaScript Code:
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
<p>Welcome to the site <b id='boldStuff'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
This answer is from here
It represents the textual contents of a given HTML tag. Can also contain tags of its own.
It does literally what it says - it returns the inner content of the specified HTML element. The most minimal self contained demonstration is shown below:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
alert(document.getElementById("myElement").innerHTML);
</script>
<div id="myElement">
Hello, world!
</div>
</body>
</html>
Running the javascript code within the tag will popup a notification saying
"Hello, world!"

How can I select an <img> element programmatically using JavaScript?

I have an <img> in an HTML document that I would like to highlight as though the user had highlighted it using the mouse. Is there a way to do that using JavaScript?
I only need it to work in Mozilla, but any and all information is welcome.
EDIT: The reason I want to select the image is actually not so that it appears highlighted, but so that I can then copy the selected image to the clipboard using XPCOM. So the img actually has to be selected for this to work.
Here's an example which selects the first image on the page (which will be the Stack Overflow logo if you test it out on this page in Firebug):
var s = window.getSelection()
var r = document.createRange();
r.selectNode(document.images[0]);
s.addRange(r)
Relevant documentation:
http://developer.mozilla.org/en/DOM/window.getSelection
http://developer.mozilla.org/en/DOM/range.selectNode
http://developer.mozilla.org/en/DOM/Selection/addRange
You might also want to call s.removeAllRanges() before s.addRange(r).
What, exactly, are you trying to do? If you're using XPCOM, you're presumably writing an application or an extension for one; can't you just get the image data and put it on the clipboard directly?
My personal choice for selecting elements is jquery:
Then to get the element of your choice is:
$("img#YOURIMAGEHERE").focus();
You can swap the source of the image, as in img.src = "otherimage.png";
I actually did this at one point, and there are things you can do to pre-load the images.
I even set up special attributes on the image elements such as swap-image="otherimage.png", then searched for any elements that had it, and set up handlers to automatically swap the images... you can do some fun stuff.
Sorry I misunderstood the question! but anyways, for those of you interested in doing what I am talking about, here is an example of what I mean (crude implementation, I would suggest using frameworks like jQuery to improve it, but just something to get you going):
<html>
<body>
<script language="javascript">
function swap(name) {
document.getElementById("image").src = name;
}
</script>
<img id="image" src="test1.png"
onmouseover="javascript:swap('test0.png');"
onmouseout="javascript:swap('test1.png');">
</body>
</html>
The basic idea of the "highLight" solution is ok, but you probably want to set a "static" border style (defined in css) for the img with the same dimensions as the one specified in the highLight method, so it doesn't cause a resize.
In addition, I believe that if you change the call to "highLight(this)", and the function def to "highLight(obj)", then you can skip the "document.getElementById()" call (and the specification of the "id" attribute for "img"), as long as you do "obj.style.border" instead.
You probably also need to spell "highLight" correctly.
Give the img tag an ID. Use document.getElementById('id').
<script type="text/javascript" language="javascript">
function highLight()
{
var img = document.getElementById('myImage');
img.style.border = "inset 2px black";
}
</script>
<img src="whatever.gif" id="myImage" onclick="hightLight()" />
EDIT::
You might try .focus to give it focus.

Categories