HTML Template Element: Clarification - javascript

I have recently discovered the HTML template element, and would appreciate some clarification.
As far as I can tell, the three distinguishing features are:
template is not rendered on screen
template does not make its way to the DOM
there is an additional content property which acts as a virtual element between the template and its contents
Aside from these, a <template> might have been a div, hidden from the screen and the DOM. In this regard, the JavaScript used to take advantage of the template is the same as if trying to fake one using a div.
Is this correct? I ask because it would be relatively easy to fake one for nonsupporting browsers.

There are some major differences:
Script (<script>) in a <template> element is not executed immediately.
Media content (<audio>, <video>, <img>) inside the template won't be loaded immedialtey.
Instead they will be executed or loaded once they are inserted in the rendered DOM tree.
querySelector() method calls and CSS selectors won't explore the content of a <template>, but you can still access the elements inside by using querySelector() on its content property.
With HTML5 template, you can access all its content in the form of a Document Fragment, and insert it in the DOM tree using appendChild(), instead of modifying innerHTML.
<template> elements can be placed in the <head> element.
You access the template content as a string using .innerHTML or as a DocumentFragment using .content.
It's quite difficult then to fake all thses behaviors. There are some polyfills that can partially do that. I'd recommend Neovov's one.
Look at this illustrative example:
//explore the content of the template
var script = T1.content.querySelector( 'script' )
console.log( script.innerHTML )
function insert() {
//insert the real templete
Target1.appendChild( T1.content.cloneNode( true ) )
//insert the fake template
Target2.innerHTML += D1.innerHTML
}
<template id=T1>
Real Template -
<script>console.log( 'executed at each insertion' )</script>
</template>
<div hidden id=D1>
Fake Template -
<script>console.log( 'executed only at parsing' )</script>
</div>
<button onclick="insert()">insert</button>
<div id=Target1><div>
<div id=Target2><div>

In short, the template tag is exactly what it sounds like.
It is just a template for the JavaScript to create in the future.
It is slightly different from a hidden <div> though, but basically you are right and it can be faked with a hidden div
Imagine this scenario where you have a webpage with 2 inputs, one that enters your name and one that enters your age. By using a template tag to create a simple table, you can then use JavaScript to populate the table with your inputs, in the same page.
This article has a good read on it:
https://www.sitepoint.com/html5-template-tag/

Related

Hide div if database contains value - Angular

I want to check if a postgresql database contains a specific value. If it is true I want to hide a HTML . Is this possible?
Can I hide elements with CSS & JS, or what should I use to hide the div?
Also, How would we add it in the Div like a NgIF statement
Thanks!
What you can do, vs what's best and the Angular way:
I assume you expect to have an AJAX call similar to:
$http.databaseAPI.get().subscribe(s => { this.hasValue == s.IsActive; });
Then, you could do a few things:
<div *ngIf="hasValue"></div>
Removes element from the DOM. Potentially very performance detrimental if overused.
<div [hidden]="!hasValue"></div>
Hides the element in the DOM.
<div [ngClass]="{'hideme': hasValue === false}"></div>
Changes the CSS based on an expression, and would require supporting CSS to hide the element.
Welcome to stackoverflow. You can get all that information from angular docs
*ngIf removes/adds the html elements from the html tree.
<div *ngIf="condition">Content to render when condition is true.</div>

What are the other options for inserting HTML generated from Javascript into the DOM besides .innerHTML?

Common practice is to place dynamic generated HTML in a container element using .innerHTML. It makes logical sense for static positioned elements that fit in the page flow.
What if you are generating HTML elements that are being positioned with FIXED? Is it necessary to create a placeholder element and use placeholder.innerHTML to insert the generated element into the DOM? Using a placeholder seems a bit counter-intuitive since the new HTML won't actually be displayed in that position in the rendered document flow.
Also, Is there performance implications if you were generating a large number of fixed elements? Is there a faster way to tell the browser "Here's an element I want rendered in fixed position on top of everything else." ?
You can use the insertAdjacentHTML() method.
document.querySelector('div').insertAdjacentHTML('beforebegin', 'beforebegin')
document.querySelector('div').insertAdjacentHTML('afterbegin', 'afterbegin')
document.querySelector('div').insertAdjacentHTML('beforeend', 'beforeend')
document.querySelector('div').insertAdjacentHTML('afterend', 'afterend')
<div style='border: solid 1px red'>
<br>
Some text
<br>
</div>
Alternatively, you could also use appendChild() with a text node like so:
var txt = document.createTextNode('Some more text')
document.querySelector('div').appendChild(txt)
<div>
Some text
<br>
</div>
Fortunately, someone on Discord provided an answer.
It appears I was asking the wrong question. I needed to use innerHTML, but I could do it on the body as an append instead of overwriting innerHTML in a placeholder container.
document.body.innerHTML += someHtml;
This will append the html to the end of the document, which eliminates the need for a container and implies intent.
There was no mention of performance or alternatives that don't modify the DOM, but I suspect this method is as good as it gets.

Attributes for .setAttribute method

I'm new to javaScript and I'm watching a lynda dot com video on JavaScript Essentials by Simon Allardice. In lesson 22, he goes over how to change DOM elements using JS. In an example, he uses .setAttribute(“align”, “right”); to change the alignment of some paragraph text to align right witin a div tag.
Does anyone know where I can find a reference list of available attributes to use for other DOM elements? I tried to search "javascript attributes reference list", but it returns html attributes.
HTML element and DOM element are synonymous. In the example you are using javascript to set HTML (DOM) element attributes. Here is a good resource.

How to get element from template by javascript?

I dont know good method how to get DOM element from template by javascript.
Example template:
<script id = "template" type="text/template">
<div>text1</div>
<div>text2</div>
<div>text3</div>
</script>
For example i want get div with "text2"
There is ways which i know, all of them are bad:
Add "class" to all elements - it breaks semantics (class created for CSS). In big projects you must use very long names for classes, its very inconvenient.
Get element by his number (index) - when adding a new element, you must rewrite old numbers in your code.
I see a couple of options:
If you don't want to use class , you can use a data-* attribute.
Assuming you load the template once and then duplicate its contents as desired, you could put id values on the elements in the template, which you then remove when cloning them and adding them to the document (so you don't end up with the same id on more than one copy of the element, which would be invalid and probably counterproductive).
Maybe you can also create as many templates as you need.
One for each div.
If you need to get each div at a time you must set ids to them ... of course you can also browse the dom inside script element to find the one you're interested in ...
Home this helps
Regards
mimiz

Getting text from a paragraph in jquery

This might be a very simple thing in jquery but I am not able to figure it out. My html document has the following structure
<div class="body">
<p>This is the text I want to extract</p>
</div>
I tried this
$("body").find("a p").text()
but this does not seem to be working for me. I am able to get the paragraph object but not the text. I tested it with console.log with no use.
What you have should be working (you can test it here), make sure you're running it when the DOM is ready though, like this:
$(function() {
alert($("body").find("a p").text()); //or just $("a p").text()
});
If it runs earlier, the elements may not be ready, and your selector won't find any matches.
If you want to select the class body make sure to use ".body" instead of "body" (which would select the <body> element). Here's a version using the .class selector:
$(function() {
alert($(".body a p").text());
});
the .html() function retrieves a nodes inner html.
$('.body a p').html();
should do the trick
Not sure if this would cause a problem, but you have invalid markup. From "The global structure of an HTML document" by the W3C
Generally, block-level elements may contain inline elements and other block-level elements. Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.
a elements are supposed to be contained by block elements like p, not the other way around.
here is your paragraph element in html or php file which is id assign tt
<p id="tt">ALert Message </p>
in in jquery file to get the text of your paragraph with tt id can be
var tt = $("#tt").text();
alert(tt);
working fine for jquery-3.1.1.js

Categories