dojo equivalent of document.X - javascript

What will be the dojo equivalent code of following.?
var msgContainer = document.createElement('div');
msgContainer.id = 'alert'; // set id of div
msgContainer.setAttribute('role', 'alert');
msgContainer.className = 'contenthide' // set class name
msgContainer.appendChild(document.createTextNode(msg));
document.body.appendChild(msgContainer);
var div = dojo.byId('alert');
while (div) {
div.parentNode.removeChild(div);
div = dojo.byId('alert');
}

var msgContainer = dojo.create("div", {
id:"alert",
role:"alert",
"class":"contenthide",
innerText:msg }, dojo.body());
Please check on the Dojo Toolkit's documentation for more DOM functions.

Related

Anchor dynamic element with click event

I am trying to dynamically add an anchor element through Javascript. The problem I have is the onclick event is not firing. I believe the problem is how I am generating the HTML. I am creating an array and then push my HTML code to the array. After I have created my output I am joining the array and then adding it to the div tag I have.
var itemLink = new Object();
itemLink.LinkName = "Edit User";
itemLink.LinkListClass = "";
itemLink.LinkListRole = "";
itemLink.LinkFunction = function() {
//do something specific with rowItem variable
alert(rowItem);
}
var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;
var output = [];
output.push('<table>');
output.push('<thead>');
output.push('<tr><th>col1</th><th>col2</th></tr>');
output.push('</thead>');
output.push('<tbody>');
output.push('<tr><td>col1 data</td><td>col2 data</td></tr>');
output.push('</tbody></table>')
var d1 = document.createElement('div');
d1.appendChild(aTag);
output.push(d1.innerHTML);
var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');
<div id="mainViewer"></div>
When I generate the output without the use of the array and joining of the output, the anchor element gets created and the onclick event works just fine.
Any ideas?
I will have multiple anchor links and I don't want to hardcode the function name. I want the onclick event to fire whatever function the itemLink Object has set.
What's the problem? You bind a function to a temp DOM element, then append its html, not its events (that's how innerHTML works). So when a link appended to the DOM, it's a different DOM link, so although the link looks the same it's not.
So, what is the solution? to push a DOM element instead of string, something like this:
//var itemLink = new Object();
//itemLink.LinkName = "Edit User";
//itemLink.LinkListClass = "";
//itemLink.LinkListRole = "";
//itemLink.LinkFunction = function() {
//do something specific with rowItem variable
//alert(rowItem);
//}
var itemLink = {
LinkName: "Edit User",
LinkListClass: "",
LinkListRole: "",
LinkFunction: function() {
//do something specific with rowItem variable
alert(rowItem);
}
};
var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;
var output = [];
output.push('<table>');
output.push('<thead>');
output.push('<tr><th>col1</th><th>col2</th></tr>');
output.push('</thead>');
output.push('<tbody>');
output.push('<tr><td>col1 data</td><td>col2 data</td></tr>');
output.push('</tbody></table>')
var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');
var d1 = document.createElement('div');
d1.appendChild(aTag);
mainView.appendChild(d1)
<div id="mainViewer"></div>
Thanks to #David Thomas for his comment :)

Shortest way to create a DIV

What would be the shortest way to do the following :
var div = document.createElement('div');
div.className = 'divClass';
div.innerHTML = 'Div Content';
... without any external libraries
class Div {
constructor(className, innerHTML) {
let div = document.createElement("div");
div.className = className;
div.innerHTML = innerHTML;
return div;
}
}
let innerHTML = "LOL"
new Div(divClass, innerHTML);
This would be the shortest way to doing it again and again while still having some order inside your code, IMO.
Write a function to do it in one line:
function tag(tagNameAndClass, innerHTML) {
var parts = (tagNameAndClass || 'div').split(/\./g);
var elem = document.createElement(parts.shift());
elem.className = parts.join(' ');
if (innerHTML) elem.innerHTML = innerHTML;
return elem;
}
Examples of uses:
tag('div.divClass', 'Div Content') // <div class="divClass">Div Content</div>
tag('.class-one.class-two', 'Content') // <div class="class-one class-two">Content</div>
tag('h1.super', 'My Super Heading') // <h1 class="super">My Super Heading</h1>
What would be the shortest way to do the following [...]
We can imagine a situation in which the div already exists in the DOM while the CSS style rule display:none ensures it remains absent from the visible document flow.
The following single line in javascript will make the element reappear into the visible document flow:
document.getElementsByClassName('divClass')[0].style.display = 'block';
Probably the best solution I have came up with so far :
var el = function(type,props,appends){
var el = document.createElement(type);
if(props) for(var x in props) el[x] = props[x];
if(appends) for(var x in appends) el.appendChild(appends[x]);
return el;
}
and then when using it (creating a popup with header and body example) :
$title = el('div',{className:'title',innerHTML:'Item Title'});
$remove = el('div',{className:'remove',innerHTML:'X'});
$header = el('div',{className:'header'},[$title,$remove,el('div',{className:'clear'})]);
$body = el('div',{className:'body',innerHTML:'body'});
$el = el('div',{className:'item'},[$header,$body]);

creating new elements using object oriented javascript

I am learning how to write object oriented javascript. I have a simple class to create div elements, but when I test the code no new elements are created. Am I doing this correctly? I am using the following code:
function elementCreation(elementParent, elementId, elementText) {
this.elementParent = document.getElementsByTagName(elementParent)[0];
this.elementId = elementId;
this.elementHtml = elementText;
this.elementMake = function (type) {
newElement = document.createElement(type);
// add new element to the dom
this.elementParent.appendChild(newElement);
};
}
var newObject = new elementCreation('body', 'testdiv', 'some text here!!!');
newObject.elementMake('div');
Your code works perfectly, congratulations.
You simply can't see an empty div without styling.
See here a demonstration with styling :
div {
width:100px;
height:100px;
background-color:red;
}​
Note that if your construction parameters were intended for the construction of the child element, you have to put them to some use. For example :
function elementCreation(elementParent, elementId, elementText) {
this.elementParent = document.getElementsByTagName(elementParent)[0];
this.elementId = elementId;
this.elementHtml = elementText;
this.elementMake = function (type) {
newElement = document.createElement(type);
// add new element to the dom
this.elementParent.appendChild(newElement);
newElement.innerHTML = elementText;
};
}
Demonstration
I won't try to use the elementId parameter : if you define a function, it's probably to call it more than once and an id can't be used more than once in HTML.
The div is being created but you aren't setting it's content as your third argument elementText.
newElement = document.createElement(type);
newElement.innerHTML = this.elementHtml; // <-- set its content
newElement.id = this.elementId; // <-- set the ID
// add new element to the dom
this.elementParent.appendChild(newElement);
Added compatibility with firefox when setting text content, then associated the id attribute to the new element. I also tried another approach that could be easier to complexify.
What about:
function elementCreation(args) {
this.parent = args.parent;
this.id = args.id;
this.text = args.text;
this.make = function(type) {
var el = document.createElement(type);
el.id = this.id;
// firefox do not support innerText, some others do not support textContent
if (typeof el.innerText != "undefined") {
el.innerText = this.text;
} else {
el.textContent = this.text;
}
this.parent.appendChild(el);
}
}
new elementCreation({
parent: document.body,
id: 'div1',
text: 'some text here!!!'
}).make('div');
You can try it with this jsfiddle.

CreateElement with id?

I'm trying to modify this code to also give this div item an ID, however I have not found anything on google, and idName does not work. I read something about append, however it seems pretty complicated for a task that seems pretty simple, so is there an alternative? Thanks :)
g=document.createElement('div'); g.className='tclose'; g.v=0;
You should use the .setAttribute() method:
g = document.createElement('div');
g.setAttribute("id", "Div1");
You can use g.id = 'desiredId' from your example to set the id of the element you've created.
var g = document.createElement('div');
g.id = 'someId';
You can use Element.setAttribute
Examples:
g.setAttribute("id","yourId")
g.setAttribute("class","tclose")
Here's my function for doing this better:
function createElement(element, attribute, inner) {
if (typeof(element) === "undefined") {
return false;
}
if (typeof(inner) === "undefined") {
inner = "";
}
var el = document.createElement(element);
if (typeof(attribute) === 'object') {
for (var key in attribute) {
el.setAttribute(key, attribute[key]);
}
}
if (!Array.isArray(inner)) {
inner = [inner];
}
for (var k = 0; k < inner.length; k++) {
if (inner[k].tagName) {
el.appendChild(inner[k]);
} else {
el.appendChild(document.createTextNode(inner[k]));
}
}
return el;
}
Example 1:
createElement("div");
will return this:
<div></div>
Example 2:
createElement("a",{"href":"http://google.com","style":"color:#FFF;background:#333;"},"google");`
will return this:
google
Example 3:
var google = createElement("a",{"href":"http://google.com"},"google"),
youtube = createElement("a",{"href":"http://youtube.com"},"youtube"),
facebook = createElement("a",{"href":"http://facebook.com"},"facebook"),
links_conteiner = createElement("div",{"id":"links"},[google,youtube,facebook]);
will return this:
<div id="links">
google
youtube
facebook
</div>
You can create new elements and set attribute(s) and append child(s)
createElement("tag",{attr:val,attr:val},[element1,"some text",element2,element3,"or some text again :)"]);
There is no limit for attr or child element(s)
Why not do this with jQuery?
var newDiv= $('<div/>', { id: 'foo', class: 'tclose'})
var element = document.createElement('tagname');
element.className= "classname";
element.id= "id";
try this you want.
that is simple, just to make a new element with an id :
var myCreatedElement = document.createElement("div");
var myContainer = document.getElementById("container");
//setAttribute() is used to create attributes or change it:
myCreatedElement.setAttribute("id","myId");
//here you add the element you created using appendChild()
myContainer.appendChild(myCreatedElement);
that is all
I'm not sure if you are trying to set an ID so you can style it in CSS but if that's the case what you can also try:
var g = document.createElement('div');
g.className= "g";
and that will name your div so you can target it.
window.addEventListener('DOMContentLoaded', (event) => {
var g = document.createElement('div');
g.setAttribute("id", "google_translate_elementMobile");
document.querySelector('Selector will here').appendChild(g);
});

Increment ID Number (JS)

I'm using jQuery Selectbox plugin which has this function:
function setupContainer(options) {
var container = document.createElement("div");
$container = $(container);
$container.attr('id', elm_id+'_container');
$container.addClass(options.containerClass);
return $container;
}
... it applies the same ID name to all dropdowns, how do I modify the above code so each id is numbered (starting from 1) and unique?
View the full script here.
Thanks!
You could store elm_id as a property of your function like this
function setupContainer(options) {
var container = document.createElement("div");
$container = $(container);
var elm_id = setupContainer.uid++;
$container.attr('id', elm_id+'_container');
$container.addClass(options.containerClass);
return $container;
}
setupContainer.uid = 1;
This way you don't rely on another global variable.
i'm presuming elm_id is a number and it's a global variable.If so the code would look like this:
function setupContainer(options) {
var container = document.createElement("div");
$container = $(container);
elm_id++;
$container.attr('id', elm_id+'_container');
$container.addClass(options.containerClass);
return $container;
}

Categories