How to bind css classes to angular2 elements, post-compiling? - javascript

If I insert the html code directly in the HTML obviously that the css is noted and the element is correctly displayed.
However, if I try to dinamically create the element in javascript and insert it the css classes won't be recognized.
For example, I've tried:
var el = document.createElement("div").setAttribute("class","some_class");
(...).appendChild(el).
And el does not obey to the css rules set by some_class
The only way I've been able to do this is directly change the element properties in javascript:
var el = document.createElement("div").style.width = "20px"; //this works
(...).appendChild(el).
The element is correctly styled.
Unfortunately I wanted to go by the class names / ids.
So, any idea on how to do this? How exactly can I bind the newly created elements in javascript via _ngcontent-vkl-6 tags created after angular2 compiling?

Use Renderer or Renderer2 (if using angular 4+):
constructor(private renderer: Renderer) {}
createElement() {
const element = this.renderer.createElement(theElementToAppendTo, 'div');
this.renderer.setElementAttribute(element, 'class', 'some_class');
}
The way you're doing it isn't safe for angular, DOM manipulation should only be done via the Renderer or other bindings such as HostBinding.
This example uses the Renderer:
https://angular.io/docs/js/latest/api/core/index/Renderer-class.html
But if you're using angular 4+ you should use Renderer2 which has a different api:
https://angular.io/docs/ts/latest/api/core/index/Renderer2-class.html
I hope this helps.

Related

how to create new tags in html

so im wanting to create new tags in html.
by this I mean like:
<imagebutton src="cool.gif" onclick="alert('you clicked the image!')">
<!-- New tag (^) loads an image and lets it have an onclick event -->
Im wondering how to do this in javascript.
is and if so, how can I do this?
Below method is used to create a custom HTML element
document.registerElement()
Below script would add the following HTML tag to the end of the element
var customElement = document.registerElement('x-custom');
document.body.appendChild(new customElement());
Custom HTML Elements
<x-custom> </x-custom>
maybe you can try this code :
document.getElementById('tag-id').innerHTML = '<ol><li>html data</li
</ol>';
just improve it
You would need to create your own javascript which manipulates your custom html elements and replaces those elements with the desired elements(which do the function). You can refer other frameworks like knockout or angular which manipulate custom attributes and elements.
There's an interesting and in depth article from HTML5Rocks.com on how to work with custom elements : Custom Elements: Defining New Elements in HTML
Here's an excerpt from the article on how to do it.
Instantiating elements
The common techniques of creating elements still apply to custom elements. As with any standard element, they can be declared in HTML or created in DOM using JavaScript.
Instantiating custom tags
Declare them:
<x-foo></x-foo>
Create DOM in JS:
var xFoo = document.createElement('x-foo');
xFoo.addEventListener('click', function(e) {
alert('Thanks!');
});
Use the new operator:
var xFoo = new XFoo();
document.body.appendChild(xFoo);

Simple DOM manipulation in custom aurelia atttribute

I am experimenting with Aurelia custom attribute by testing a simple DOM manipulation.
To my surprise performing the manipulation by appending and ellipse node to the parent svg node does modify the HTML but doesn't render the ellipse.
Manipulating the innerHtml property does work as expected.
import { bindable, inject} from 'aureliaframework';
#inject(Element)
export class TestCustomAttribute {
constructor(private element: SVGElement) {
}
attached()
{
var ellipse = document.createElement("ellipse");
ellipse.setAttribute("cx","200");
ellipse.setAttribute("cy","200");
ellipse.setAttribute("rx","100")
ellipse.setAttribute("ry","100")
ellipse.setAttribute("style","fill:blue")
//this is rendered
this.element.innerHTML = "<ellipse style='fill: purple' cx='200' cy='200' rx='100' ry='100'></ellipse>"
//this shows on DOM explorer but not rendered
this.element.appendChild(ellipse)
}
Is it possible to achieve the desired result using appendNode() instead of manipulating the element innerHtml?
Looks like this is more of a quirk around the DOM API and SVG elements, rather than an issue with Aurelia.
Try using createElementNS and include the svg namespace instead https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS
See this question for more details: jquery's append not working with svg element?

Do custom HTML elements inherit parent CSS styles?

When creating custom elements in HTML, does the child tag inherit the parent's CSS styles?
Here is my test case, from Chrome:
var h1bProto = document.registerElement ('h1-b',
{
prototype: Object.create (HTMLHeadingElement.prototype),
extends: "h1"
});
When I append a child using the new h1bProto it generates an H1 tag with is="h1-b", example below:
var node = document.body.appendChild (new hibProto());
node.textContent = "Hello";
<h1 is="h1-b">Hello</h1>
Hello
This gives me the parents CSS styles. However, if I add a node by creating the element first, then appending the node, the code looks like this:
var node = document.createElement ("h1-b");
node.textContent = "Hello";
document.body.appendChild (node);
<h1-b>Hello</h1-b>
Hello
Am I missing something, or do children not inherit the parent's CSS styles? If they don't, then is the best work around to use the Shadow DOM?
According to the W3 spec you aren't going crazy!
Trying to use a customized built-in element as an autonomous custom
element will not work; that is, Click
me? will simply create an HTMLElement with no special
behaviour.
Aka, in your example making a tag with <h1-b> will not apply the styling or behavior of an <h1> tag. Instead you must create an <h1> tag with the is attribute set to the name of your custom element. The section I linked you to in the spec actually does a great job explaining how to go about creating the tag.
All in all, you just need to make your element like so:
document.createElement("h1", { is: "h1-b" });
One reason that comes to mind for this is that most bots don't parse your javascript. As a result they would have a challenge to figure out what the elements in your dom really are. Imagine how much your seo would tank if a bot didn't realize that your <h1-b> elements were really <h1> elements!

jQuery: DOM Elements: Attributes: query & create

I have a few questions about jQuery, relating to attributes:
Is there a jQuery or DOM API call that I could use to list or clone all of the attributes of a DOM element. The jQuery.attr() API call lets you do it if you know the name of the attribute, but if you don't, is there a way?
Is there a jQuery or DOM API call that I could use to create a new CSS rule, besides the obvious one of dynamically loading a new script?
It seems possible because when I open up the JS debugger in Google Chrome using CTRL-Shift-J, and click on a DOM element in the elements pane, I can see all of the attributes of the element without having to ask for them by name.
Clone the whole object, that will replicate all attributes as well, http://api.jquery.com/clone/
Add new style section into the head element using append, http://api.jquery.com/append/
The other guys are right that you should use clone - but if you want to list the attributes, you can do it like so:
for(attr in $('#selector')) {
console.log(attr);
}
I don't think you can create a new css rule, but you can do pretty much the same by attaching css to a selector:
$('#selector').css({
display: 'block'
});

How can I set a css ":hover" on a DOM created element in JavaScript?

I'm using the DOM to manage a JSON response from an AJAX function I'm running. The script I'm writing needs to be completely portable, so I am defining the styles for the created elements on the fly (meaning, no linking to an external CSS, and no providing CSS in the HTML doc itself, because I won't have control of the doc).
I'd like to create a hover effect on some of the elements.
example:
#myDiv:hover { background:#000000; }
Is there a way to define that in the DOM? Or do I have to use mouseover?
You can dynamically create and manipulate stylesheets. See here for some of the cross-browser issues with this approach.
I've got a wrapper function lying around which works around some of them; using it, the code would read
document.createStyleSheet().addRule('#myDiv:hover', 'background:#000000;');
you may create element with predefined class:
.h:hover{color: #c00}
var elem = document.createElement('div');
elem.className = 'h'

Categories