As we all know to change HTML element's HTML content using JavaScript "innerHTML" property is commonly used. This "innerHTML" property is used on an HTML element object like(document.getElementById("demo").innerHTML = 5 + 6;)
My doubt is why the "innerHTML" property can't be used as an attribute in any HTML element?
As per my knowledge and understanding attribute and property have the same semantic meaning.
So, why the below code can not work?
<p id="demo" innerHTML="Jumbo"></p>
Because not all JavaScript properties on a DOM element equate to attributes.
.innerHTML provides a way to get or set the stuff that goes between the start and end tag. So if you want to put stuff there, just put it there:
<p id="demo">Jumbo</p>
Edit: To answer your questions below, the DOM is a conceptual representation of HTML in code (in this case JavaScript), so a DOM element is a JavaScript object that you can use to access and manipulate an HTML element (an element is a portion of an HTML document that starts and ends with a tag, so <b><span>Hello!</span></b> contains two elements, a b element and a span element.
To use .innerHTML to get the content of an element, all you need to do is access it in an expression instead of assigning a value to it.
Example:
var d = document.getElementById('myDiv');
console.log(d.innerHTML); // <em>Jumbo</em>
<div id="myDiv"><em>Jumbo</em></div>
Related
I'm trying to change the id 'character' to 'characterSelected'
var character = document.getElementById('character');
var characterSelected = document.getElementById('characterSelected');
function klik() {
character.innerHTML = characterSelected;
}
character.addEventListener('click', klik);
This is what I have so far but it doensn't seem to work. I want to do this using Javascript only, no jQuery.
Thanks
You tried something, it didn't work. Now is the time to look up the standard properties and functions you're using incorrectly. If guessing doesn't work, always look for reliable documentation.
A good reference would be the Mozilla Developer Network (MDN). It's a wiki-style encyclopedia about the web, its standards and current browser compatibility. If you look at the page about innerHTML, you'll find the following:
The Element.innerHTML property sets or gets the HTML syntax describing
the element's descendants.
This means that the innerHTML property is used to replace the content of a tag as if you wrote that HTML inside it. Not what you want.
What you wanted was to change the id of an element. If you search for element id, you'll land on the Element.id page. And how practical, there's an example:
var idStr = elt.id; // Get the id.
elt.id = idStr; // Set the id
However, this is not going to fix your issues. You see, you guessed wrong when trying to use the getElementById function. This function looks at the page and finds the element with that id right now. If you don't have any element with the characterSelected id at first, then this variable you set is going to be null for the rest of time. Variables won't magically update when an element with that id is placed in the page.
And finally, you have missed the purpose of the id attribute itself.
Its purpose is to identify the element when linking (using a fragment
identifier), scripting, or styling (with CSS).
The purpose of an id is to identify an element uniquely. You might think: "that's what I'm doing". No. You're using an id to represent whether or not an element is selected. This is wrong. Depending on your objective, I would say: just store the selected element inside a variable. Then whenever you need to do something with the selected element, it's in that variable. If you need specific style for that element, then you could set a class to it. But the id isn't meant for this at all - in fact, an id isn't meant to change once an element is placed.
Is the code bellow allowed in html ?
<img src=<script>Some javascript</script> >
I know I can set attribute in javascript with setAttribute, but I would like to do it differently.
No, it is not. It is nowhere near to valid HTML, as you can check with a validator. Besides, an attribute value is taken as text; no tags are interpreted there.
To set an attribute of an HTML element in JavaScript, you can use setAttribute or directly assign to a property of the element node (the src property in this case).
You are not telling why you would not do things that way, but there is another way, though it is old-fashioned and risky: in a place where you would put an img element, you can write
document.write('<img src=' + someVariable + ' alt="">');
That is, you would generate the entire img element, in serialized form that will then be parsed by the browser.
A better way to add an element that is not in the document statically is to use document.createElement, do some assignments, and then add the created element into the document tree e.g. with the appendChild method of a suitable element.
what DOM elements is document.getElementById("id").value used for ?
i mean can i use it with an element like heading tags etc
or it is used with the items have a value attribute [textboxes ] etc
and what is the difference .innerHTML and .value properties
what DOM elements is document.getElementById("id").value used for ?
You can use getElementById to get a reference to any element that has an id attribute on it.
and what is the difference .innerHTML and .value properties
They're completely unrelated. innerHTML is the HTML representation of the contents of the element. value is the value of a form control element like an input.
For example, suppose we have:
<div id="foo">Hey <strong>you</strong></div>
You can do this:
console.log(document.getElementById("foo").innerHTML);
...which will likely give you something like this in the console:
Hey <STRONG>you</STRONG>
Note that this is not exactly the same as what was in your document; when you read the value of innerHTML, the browser makes a string from what's actually currently present in the DOM, using its rules for how to create that string.
You can also set it to change the contents.
In contrast, with a form control:
<input id="bar" type="text" value="Text field value">
console.log(document.getElementById("bar").value);
...which gives you
Text field value
Setting the value is normally used for input/form elements. innerHTML is normally used for div, span, td and similar elements.
Here is a link showing the use of ID.value:
http://www.javascript-coder.com/javascript-form/javascript-form-value.phtml
and
The getElementById() method accesses the first element with the specified id.
and
yes, you can use it with an element like heading tags etc
How would you access the value of an em tag in javascript?
This is the element I'm trying to access: <em id='tag_IS_System_Agent'></em>
which displays: John Smith
I'm trying to access it via javascript:
document.getElementById("emailFrame").src
= "http://www.website.org/mail.php?cid="
+IS_ATTR_ID.value
+"&name="+document.write("<em id=\"tag_IS_System_Agent\"> <\/em>")
+"&em="+email;`
Any idea? I know that document.write("<em id=\"tag_IS_System_Agent\"> <\/em>") is wrong and I'm stumped and not sure what to do.
Accessing the value based on your markup would be:
var myValue = document.getElementById("tag_IS_System_Agent").textContent
By “the value of an ‘em’ tag”, you apparently mean the content of an em element. If the element has an id attribute, as in your example, you can use the getElementById method of document to access the element node in the DOM. Then you can get the content of the element, serialized as HTML, using the innerHTML property. Note that this will include markup for inner elements, if any. So the expression you would use would be
document.getElementById('tag_IS_System_Agent').innerHTML
Instead of innerHTML, you could use textContent, which gives you just the textual content, without any inner tags. However, this is less widely supported (e.g., not in IE 8). If there is no inner markup, the results are the same, but innerHTML is thus safer.
I want to know what the difference is between appendChild, insertAdjacentHTML, and innerHTML.
I think their functionality are similar but I want to understand clearly in term of usage and not the execution speed.
For example, I can use innerHTML to insert a new tag or text into another tag in HTML but it replaces the current content in that tag instead of appends.
If I would like to do it that way (not replace) I need to use insertAdjacentHTML and I can manage where I want to insert a new element (beforebegin, afterbegin, beforeend, afterend)
And the last if I want to create (not insertion in current tag) a new tag and insert it into HTML I need to use appendChild.
Am I understanding it correctly? Or are there any difference between those three?
element.innerHTML
From MDN:
innerHTML sets or gets the HTML syntax describing the element's descendants.
when writing to innerHTML, it will overwrite the content of the source element. That means the HTML has to be loaded and re-parsed. This is not very efficient especially when using inside loops.
node.appendChild
From MDN:
Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.
This method is supported by all browsers and is a much cleaner way of inserting nodes, text, data, etc. into the DOM.
element.insertAdjacentHTML
From MDN:
parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. [ ... ]
This method is also supported by all browsers.
....
The appendChild methods adds an element to the DOM.
The innerHTML property and insertAdjacentHTML method takes a string instead of an element, so they have to parse the string and create elements from it, before they can be put into the DOM.
The innerHTML property can be used both for getting and setting the HTML code for the content of an element.
#Guffa did explain the main difference ie innerHTML and insertAdjacentHTML need to parse the string before adding to DOM.
In addition see this jsPerf that will tell you that generally appendChild is faster for the job it provides.
One that I know innerHTML can grab 'inner html', appendChild and insertAdjacentHTML can't;
example:
<div id="example"><p>this is paragraph</p><div>
js:
var foo = document.getElementById('example').innerHTML;
end then now
foo = '<p>this is paragraph</p>';
DOCS:
appendChild
insertAdjacentHTML
innerHtml
innerHTML vs appendChild() performance
insertAdjacentHTML vs innerHTML vs appendChild performance
the main difference is location (positioning) :
(elVar mean element saved to variable)
** elVar.innerHTML: used to sets/get text and tags (like ) inside an element (if u use "=" it replace the content and "+=" will add to the end.
** divElvar.appendChild(imgElVar): to add pure element to the end of another element (or start with prepend) .
** insertedElVar.insertAdjacentElement(beforebegin,targetElvar): it insert element into spicific location before elVar (after it with "afterend").
-innerText: can replace/get/insertOnEnd text.but can read tags and text inside element with display:hidden , cant insert on start .
-innercontent : show all text inc hidden , cant read html tags and it put empty spaces instead of them , cant insert on start
-innerHTML: read all set all , cant insert on start
-prepend : insert text at start of elvar (but cant use to get/replace text or html)
prepend was needed for start, after it made its easy to make append , not for a need , its just bcz lol