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.
Related
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>
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
I am modifying a javascript file in which they have used the following code. Does anyone know what this does / where it is documented / etc. It appears it is creating an anchor node and giving it the inner html of "Back", but I'm not sure how it works or what it's capabilities are, as I need to add various attributes to the link:
$("<a id=>").html("Back");
Thanks!
jQuery is just being forgiving. Normally, the code would look like this, instead:
$('<a/>').html("Back");
Which means, create an a element and set its inner HTML to "Back". You can chain some attribute assignments directly after:
$('<a/>')
.html('Back');
.attr('id', 'your-id');
This code is indeed creating an anchor element:
<a id="">Back</a>
You can add attributes using the "attr" function, like so:
$("<a id=>").html("Back").attr('href', myUrl);
Alternatively, you can add the attributes directly in the markup:
$("<a id='myId' href='url'>").html("Back");
It is creating an anchor element, but it hasn't appended it to anything, what you would normally do, is either:
$("body").append($("<a>").html("Back").attr("target", "_blank"));
(as an example), or even:
$("<a>").html("Back").attr("target", "_blank").appendTo($("body"));
Because it is a jQuery object, you can continue chaining methods on it to build it up how you want to.
I think it's just some bothched HTML being passed to the factory. Should result in a jQuery collection holding one anchor element which is not yet in the DOM and which has an empty id attr and contains the text "Back":
<a id="">Back</a>
what is the meaning of these jquery random attributes in html and how jquery use them
any ideas please ??
This is the jQuery expando attribute, it's a bit random because it's generated on page load, it's "jQuery" + (new Date()).getTime() (to avoid possible naming conflicts) but you'll notice the attribute is the same for all elements.
This is they key in $.cache for the element's events and data...it's stored this way for a few reasons, the main is to avoid circular references. The ID is actually $.uuid which is just an incrementing counter used for each element's key in $.cache.
You can get the current attribute in jQuery 1.4+ with a simple alert($.expando), for an example of how it's used, say you wanted the data for that #wmd-preview element, doing this:
$("#wmd-preview").data()
Is doing this:
$.cache[$("#wmd-preview")[0][$.expando]]
Also note that jQuery intentionally strips these out when you call .html() to get the content.