Different ways of creating a div [duplicate] - javascript

This question already has answers here:
What is the most efficient way to create HTML elements using jQuery?
(12 answers)
Closed 7 years ago.
Is there any significant difference in how the new DOM element is created? Are there any advantages/disadvantages of using one way over another or does it come down to personal preference? I usually use the first way and only recently found out about the second one.
var test1 = $('div#test1'),
test2 = $('div#test2')
;
// first way
$('<div/>')
.addClass('mainClass subClass')
.attr('id', 'someId2')
.attr('data-extra', 'extraInfo')
.text('some text')
.appendTo(test2)
;
// second way
$('<div/>',
{
'class': 'mainClass subClass',
'id': 'someId1',
'data-extra': 'extraInfo',
'text': 'some text'
})
.appendTo(test1)
;

I think different ways are differ in performance , put not completely sure the from the perfect answer
i am using pure javascript
var element = document.createElement("div");
var elementContent = document.createTextNode("My div");
element.appendChild(elementContent);
// add div to body
document.body.appendChild(element);

Second example will be faster compared to first.
In case of first. The object is created and returned. And then you are using jquery methods which gets the jquery object of element everytime and sets the new classes/attributes.
In case of second approach, it iterate over the collection of properties to create the dom element along with those attributes and classes.

Related

javascript: Create variables/const for all elements in qureySelectorAll [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed last year.
I have multiple in my code, each with class="output" and unique IDs.
<p>Workers: <span class="output" id="workersOutput">0</span><span class="output" id="workersProdOutput"></span></p>
I want to use querySelectorAll to get them addressable in js via variables/const so that I can change their values with textContent.
Individually, I would do the following to find each div, and then the second line to update it on screen.
const workersOutput = document.getElementById('workersOutput');
workersOutput.textContent = `${workers}`;
This is really messy though when I'll have many of these to do (12 at the moment, more to come).
Using querySelectorAll, I can make some hybrid version, using their individual index numbers from the node list. It's not exactly readable or easy to use, as the data attached to each is only visible if I output it somewhere. Not to mentioned if I add more divs, those numbers will change and not be assigned to the same IDs anymore.
const outputs = document.querySelectorAll('.output');
outputs[2].textContent = `${workers}`;
Couldn't I use maybe forEach to create a variable for each using the ID attached to that index number? Or something along the lines of the below example (I know that's not how that works, but I want to get the idea across):
const outputs = document.querySelectorAll('.output');
outputs.forEach((output) => {
const outputs[2] = document.getElementById(output.id);
});
I could also be way off on how to accomplish this the "right way", I'm newish to coding.
Use an object whose property names are the IDs.
const outputs = {};
document.querySelectorAll(".output").forEach(el => outputs[el.id] = el);

how to select my first child in jQuery [duplicate]

This question already has answers here:
jQuery first child of "this"
(11 answers)
Closed 10 years ago.
I'm having a bit of trouble selecting the first child in jQuery. I'm trying to do this to avoid having LOTS of if statements. Basically, you click on a button. This class selector is setup to handle the click in my JS. Once you go into the JS, I want to get the child of the item that was just clicked, but I'm not having any joy.
Here's what I have in my JS:
$('.itemClicked').click(function(){
var id = $(this).attr('id').first();
// it can't find the method first() here. If I just find the id, I get the
// correct ID of what I just clicked.
var test = id.first();
// I tried the above to seperate the ID from the first() method request
// no joy with this either.
test.toggleClass("icon-tick");
// this is my ultimate aim, to toggle this icon-tick class on the item
// clicked.
});
Thanks in advance if you can help me out here. I'm probably just doing something stupid but I'm struggling to realise what that is.
Your current version doesn't work because .attr('id') just returns the ID as a string, not a jQuery object. Also, .first() returns the first item from a jQuery collection, not their children.
So, you just want:
var test = $(this).children().first();
or:
var test = $('>:first-child', this);
or:
var test = $(this).children(':first');
or (on newer browsers):
var test = $(this.firstElementChild);
In a jsperf test with Chrome 25 the .firstElementChild method was incredibly fast, but it's not available on MSIE < 9. The .children().first()was the fastest portable option, and the>:first-child' method was very, very slow.
Perhaps
$('.itemClicked').click(function(){
$(':first-child',this).toggleClass('icon-tick');
});
is what you're after.
Live example: http://jsfiddle.net/ySMLG/
If all that you want to do is toggle the class "icon-tick" on the item that was click, then this will work:
$('.itemClick').click(function () {
$(this).toggleClass('icon-tick');
});
The statement:
$(this).attr('id').first()
doesn't work because the attr() method returns the value of the attribute, not the jQuery object, so it is not chainable.

Add multiple element using jquery each? [duplicate]

This question already has answers here:
Why do multiple `.appendTo` calls on a newly created jQuery element only append it once?
(2 answers)
Closed 3 months ago.
I'm new here and I'd like to ask a question about jQuery.
i have some problem with jquery each, and i have code :
$("#search-submit").click(function(){
var item = $("<span>asdf</span>");
$("body").append(item, item);
}
I just can't figure out, why is this simple code don't work. Instead of print "asdf" twice, i just got one "asdf" printed each time i click the button..
this also don't work. this is so silly...
$("body").append(item);
$("body").append(item);
Thanks a lot... and sorry about my bad english
Denny.
You can append a jQuery object only one time, you can clone the object:
$("#search-submit").click(function() {
var item = $("<span>asdf</span>");
$("body").append(item, item.clone());
})
Or append a string:
$("#search-submit").click(function() {
var item = "<span>asdf</span>";
$("body").append(item, item);
})
http://jsfiddle.net/yKyAL/
You can use clone
$("#search-submit").click(function() {
var item = $("<span>asdf</span>");
$("#test").append(item.clone(), item.clone());
});​
Check the fiddle here

Change tag using javascript [duplicate]

This question already has answers here:
Can I change an HTML element's type?
(9 answers)
Closed 4 years ago.
I want to know how can I change a tag with pure javascript like that
<span>some text</span>
I want to change it to that
<div>some text</div>
I have no idea how to do it.
You can't change the type of an element like that, instead you have to create a new element and move the contents into it. Example:
var e = document.getElementsByTagName('span')[0];
var d = document.createElement('div');
d.innerHTML = e.innerHTML;
e.parentNode.replaceChild(d, e);
Demo: http://jsfiddle.net/Guffa/bhnWR/
Just written a jQuery plugin for this.
(function( $ ) {
$.fn.replaceTag = function(newTag) {
var originalElement = this[0]
, originalTag = originalElement.tagName
, startRX = new RegExp('^<'+originalTag, 'i')
, endRX = new RegExp(originalTag+'>$', 'i')
, startSubst = '<'+newTag
, endSubst = newTag+'>'
, newHTML = originalElement.outerHTML
.replace(startRX, startSubst)
.replace(endRX, endSubst);
this.replaceWith(newHTML);
};
})(jQuery);
Usage:
$('div#toChange').replaceTag('span')
The biggest advantage of this method is that id preserves all the attributes of the original element.
If jquery is acceptable use replaceWith.
$('span').each(function() {
$(this).replaceWith($('<div>' + this.innerHTML + '</div>'));
});
Here is a JSFIDDLE working DEMO
If using jquery
Var spantxt = $('span').text();
$('body').append('<div>'+spantext+'</div');
Note this would only work if there was only one span, use an id selector otherwise
You can't do it.
What you want to do is to take content of your span,
then delete it and create new div and fill it with previous content.
Assumption: The span you want to replace is wrapped in a div with id "foo"
In pure javascript you could do something like:
var original_html = document.getElementById('foo').innerHTML;
original_html = original_html.replace("<span>", "<div>");
original_html = original_html.replace(new RegExp("</span>"+$), "</div">)
document.getElementById('foo').innerHTML=original_html;
If however you can not necessarily expect the span to be tightly wrapped by an element you can consistently get (by id or otherwise), the javascript becomes fairly complex. In either case, the real answer here is: use jQuery.

Determine if an element is block level or inline with JavaScript while walking DOM tree [duplicate]

This question already has answers here:
Closed 10 years ago.
While walking HTML5 DOM tree I want to determine whether each element is a block level element or inline element.
var divElement = document.getElementById('foo');
alert(divElement.style.display)
alert(window.getComputedStyle(divElement, null).getPropertyValue('display'))
I see that the first alert displays a null-string while the second alert displays 'block', so I think the second technique is what I need to use. Here is a jsfiddle: http://jsfiddle.net/UaFpv/
I want to know if there is any downside to using ​window.getComputedStyle(divElement, null).getPropertyValue('display') to do my job, like cross-browser compatibility issues, etc. Are there any other techniques that can solve this problem?
Old IE versions do not support getComputedStyle. For IE, use the currentStyle property:
divElement.currentStyle['display'];
Implemented in your code:
var divElement = document.getElementById('foo');
var displayStyle;
if (divElement) { // Only if the element exists
if (window.getComputedStyle) {
displayStyle = window.getComputedStyle(divElement, null).getPropertyValue('display');
} else {
displayStyle = divElement.currentStyle.display;
}
}
alert(displayStyle);

Categories