CreateElement with id? - javascript

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);
});

Related

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.

dojo equivalent of document.X

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.

jQuery: how to change tag name?

jQuery: how to change tag name?
For example:
<tr>
$1
</tr>
I need
<div>
$1
</div>
Yes, I can
Create DOM element <div>
Copy tr content to div
Remove tr from dom
But can I make it directly?
PS:
$(tr).get(0).tagName = "div";
results in DOMException.
You can replace any HTML markup by using jQuery's .replaceWith() method.
example: http://jsfiddle.net/JHmaV/
Ref.: .replaceWith
If you want to keep the existing markup, you could use code like this:
$('#target').replaceWith('<newTag>' + $('#target').html() +'</newTag>')
No, it is not possible according to W3C specification: "tagName of type DOMString, readonly"
http://www.w3.org/TR/DOM-Level-2-Core/core.html
Where the DOM renameNode() Method?
Today (2014) no browser understand the new DOM3 renameNode method (see also W3C)
check if run at your bowser: http://jsfiddle.net/k2jSm/1/
So, a DOM solution is ugly and I not understand why (??) jQuery not implemented a workaround?
pure DOM algorithm
createElement(new_name)
copy all content to new element;
replace old to new by replaceChild()
is something like this,
function rename_element(node,name) {
var renamed = document.createElement(name);
foreach (node.attributes as a) {
renamed.setAttribute(a.nodeName, a.nodeValue);
}
while (node.firstChild) {
renamed.appendChild(node.firstChild);
}
return node.parentNode.replaceChild(renamed, node);
}
... wait review and jsfiddle ...
jQuery algorithm
The #ilpoldo algorithm is a good start point,
$from.replaceWith($('<'+newname+'/>').html($from.html()));
As others commented, it need a attribute copy ... wait generic ...
specific for class, preserving the attribute, see http://jsfiddle.net/cDgpS/
See also https://stackoverflow.com/a/9468280/287948
The above solutions wipe out the existing element and re-create it from scratch, destroying any event bindings on children in the process.
short answer: (loses <p/>'s attributes)
$("p").wrapInner("<div/>").children(0).unwrap();
longer answer: (copies <p/>'s attributes)
$("p").each(function (o, elt) {
var newElt = $("<div class='p'/>");
Array.prototype.slice.call(elt.attributes).forEach(function(a) {
newElt.attr(a.name, a.value);
});
$(elt).wrapInner(newElt).children(0).unwrap();
});
fiddle with nested bindings
It would be cool to copy any bindings from the at the same time, but getting current bindings didn't work for me.
To preserve the internal content of the tag you can use the accessor .html() in conjunction with .replaceWith()
forked example: http://jsfiddle.net/WVb2Q/1/
Inspired by ericP answer, formatted and converted to jQuery plugin:
$.fn.replaceWithTag = function(tagName) {
var result = [];
this.each(function() {
var newElem = $('<' + tagName + '>').get(0);
for (var i = 0; i < this.attributes.length; i++) {
newElem.setAttribute(
this.attributes[i].name, this.attributes[i].value
);
}
newElem = $(this).wrapInner(newElem).children(0).unwrap().get(0);
result.push(newElem);
});
return $(result);
};
Usage:
$('div').replaceWithTag('span')
Working pure DOM algorithm
function rename_element(node, name) {
let renamed = document.createElement(name);
Array.from(node.attributes).forEach(attr => {
renamed.setAttribute(attr.name, attr.value);
})
while (node.firstChild) {
renamed.appendChild(node.firstChild);
}
node.parentNode.replaceChild(renamed, node);
return renamed;
}
You could go a little basic. Works for me.
var oNode = document.getElementsByTagName('tr')[0];
var inHTML = oNode.innerHTML;
oNode.innerHTML = '';
var outHTML = oNode.outerHTML;
outHTML = outHTML.replace(/tr/g, 'div');
oNode.outerHTML = outHTML;
oNode.innerHTML = inHTML;
To replace the internal contents of multiple tags, each with their own original content, you have to use .replaceWith() and .html() differently:
http://jsfiddle.net/kcrca/VYxxG/
JS to change the tag name
/**
* This function replaces the DOM elements's tag name with you desire
* Example:
* replaceElem('header','ram');
* replaceElem('div.header-one','ram');
*/
function replaceElem(targetId, replaceWith){
$(targetId).each(function(){
var attributes = concatHashToString(this.attributes);
var replacingStartTag = '<' + replaceWith + attributes +'>';
var replacingEndTag = '</' + replaceWith + '>';
$(this).replaceWith(replacingStartTag + $(this).html() + replacingEndTag);
});
}
replaceElem('div','span');
/**
* This function concats the attributes of old elements
*/
function concatHashToString(hash){
var emptyStr = '';
$.each(hash, function(index){
emptyStr += ' ' + hash[index].name + '="' + hash[index].value + '"';
});
return emptyStr;
}
Related fiddle is in this link
Since replaceWith() didn't work for me on an element basis (maybe because I used it inside map()), I did it by creating a new element and copying the attributes as needed.
$items = $('select option').map(function(){
var
$source = $(this),
$copy = $('<li></li>'),
title = $source.text().replace( /this/, 'that' );
$copy
.data( 'additional_info' , $source.val() )
.text(title);
return $copy;
});
$('ul').append($items);
Take him by the word
Taken the Question by Word "how to change tag name?" I would suggest this solution:
If it makes sense or not has to be decided case by case.
My example will "rename" all a-Tags with hyperlinks for SMS with span tags. Maintaining all attributes and content:
$('a[href^="sms:"]').each(function(){
var $t=$(this);
var $new=$($t.wrap('<div>')
.parent()
.html()
.replace(/^\s*<\s*a/g,'<span')
.replace(/a\s*>\s*$/g,'span>')
).attr('href', null);
$t.unwrap().replaceWith($new);
});
As it does not make any sense to have a span tag with an href attribute I remove that too.
Doing it this way is bulletproof and compatible with all browsers that are supported by jquery.
There are other ways people try to copy all the Attributes to the new Element, but those are not compatible with all browsers.
Although I think it is quite expensive to do it this way.
Jquery plugin to make "tagName" editable :
(function($){
var $newTag = null;
$.fn.tagName = function(newTag){
this.each(function(i, el){
var $el = $(el);
$newTag = $("<" + newTag + ">");
// attributes
$.each(el.attributes, function(i, attribute){
$newTag.attr(attribute.nodeName, attribute.nodeValue);
});
// content
$newTag.html($el.html());
$el.replaceWith($newTag);
});
return $newTag;
};
})(jQuery);
See : http://jsfiddle.net/03gcnx9v/3/
Yet another script to change the node name
function switchElement() {
$element.each(function (index, oldElement) {
let $newElement = $('<' + nodeName + '/>');
_.each($element[0].attributes, function(attribute) {
$newElement.attr(attribute.name, attribute.value);
});
$element.wrapInner($newElement).children().first().unwrap();
});
}
http://jsfiddle.net/rc296owo/5/
It will copy over the attributes and inner html into a new element and then replace the old one.
$(function(){
$('#switch').bind('click', function(){
$('p').each(function(){
$(this).replaceWith($('<div/>').html($(this).html()));
});
});
});
p {
background-color: red;
}
div {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello</p>
<p>Hello2</p>
<p>Hello3</p>
<button id="switch">replace</button>
You can use this function
var renameTag = function renameTag($obj, new_tag) {
var obj = $obj.get(0);
var tag = obj.tagName.toLowerCase();
var tag_start = new RegExp('^<' + tag);
var tag_end = new RegExp('<\\/' + tag + '>$');
var new_html = obj.outerHTML.replace(tag_start, "<" + new_tag).replace(tag_end, '</' + new_tag + '>');
$obj.replaceWith(new_html);
};
ES6
const renameTag = function ($obj, new_tag) {
let obj = $obj.get(0);
let tag = obj.tagName.toLowerCase();
let tag_start = new RegExp('^<' + tag);
let tag_end = new RegExp('<\\/' + tag + '>$');
let new_html = obj.outerHTML.replace(tag_start, "<" + new_tag).replace(tag_end, '</' + new_tag + '>');
$obj.replaceWith(new_html);
};
Sample code
renameTag($(tr),'div');
Try this one also. in this example we can also have attributes of the old tag in new tag
var newName = document.querySelector('.test').outerHTML.replaceAll('h1', 'h2');
document.querySelector('.test').outerHTML = newName;
<h1 class="test">Replace H1 to H2</h1>

How to get all elements inside "div" that starts with a known text

I have a div element in an HTML document.
I would like to extract all elements inside this div with id attributes starting with a known string (e.g. "q17_").
How can I achieve this using JavaScript ?
If needed, for simplicity, I can assume that all elements inside the div are of type input or select.
var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
if(searchEles[i].id.indexOf('q1_') == 0) {
matches.push(searchEles[i]);
}
}
}
Once again, I strongly suggest jQuery for such tasks:
$("#myDiv :input").hide(); // :input matches all input elements, including selects
Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :
var elements = document.getElementById('parentContainer').children;
Option 2: Likely slowest :
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3: Requires change to code (wrap a form instead of a div around it) :
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
With modern browsers, this is easy without jQuery:
document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');
The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".
Note that all browsers released since June 2009 support this.
Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:
function fillArray(vector1,vector2){
for (var i = 0; i < vector1.length; i++){
if (vector1[i].id.indexOf('q17_') == 0)
vector2.push(vector1[i]);
if(vector1[i].tagName == 'DIV')
fillArray (document.getElementById(vector1[i].id).children,vector2);
}
}
function selectAllElementsInsideDiv(divId){
var matches = new Array();
var searchEles = document.getElementById(divId).children;
fillArray(searchEles,matches);
return matches;
}
Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:
var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv = selectAllElementsInsideDiv('myDiv')
I have tested it and it worked for me. I hope it helps you.
var $list = $('#divname input[id^="q17_"]'); // get all input controls with id q17_
// once you have $list you can do whatever you want
var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {
var id = $(this).prop("id"); // get id
var cbx = '';
if ($(this).is(':checkbox') || $(this).is(':radio')) {
// Need to see if this control is checked
}
else {
// Nope, not a checked control - so do something else
}
});
i have tested a sample and i would like to share this sample and i am sure it's quite help full.
I have done all thing in body, first creating an structure there on click of button you will call a
function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens.
I have given alerts here on different level so u can test where r u now in the coding .
<body>
<h1>javascript to count the number of children of given child</h1>
<div id="count">
<span>a</span>
<span>s</span>
<span>d</span>
<span>ff</span>
<div>fsds</div>
<p>fffff</p>
</div>
<button type="button" onclick="selectallelement('count')">click</button>
<p>total element no.</p>
<p id="sho">here</p>
<script>
function selectallelement(divid)
{
alert(divid);
var ele = document.getElementById(divid).children;
var match = new Array();
var i = fillArray(ele,match);
alert(i);
document.getElementById('sho').innerHTML = i;
}
function fillArray(e1,a1)
{
alert("we are here");
for(var i =0;i<e1.length;i++)
{
if(e1[i].id.indexOf('count') == 0)
a1.push(e1[i]);
}
return i;
}
</script>
</body>
USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS

Categories