I\'m refactoring some old JavaScript code and there\'s a lot of DOM manipulation going on.
var d = document;
var odv = d.createElement(\"div\");
odv.style.di
It's all pretty straight forward! Heres a couple quick examples...
var $example = $( XMLDocRoot );
var $element = $( $example[0].createElement('tag') );
// Note the [0], which is the root
$element.attr({
id: '1',
hello: 'world'
});
var $example.find('parent > child').append( $element );
Not mentioned in previous answers, so I'm adding working example how to create element elements with latest jQuery, also with additional attributes like content, class, or onclick callback:
const mountpoint = 'https://jsonplaceholder.typicode.com/users'
const $button = $('button')
const $tbody = $('tbody')
const loadAndRender = () => {
$.getJSON(mountpoint).then(data => {
$.each(data, (index, { id, username, name, email }) => {
let row = $('<tr>')
.append($('<td>', { text: id }))
.append($('<td>', {
text: username,
class: 'click-me',
on: {
click: _ => {
console.log(name)
}
}
}))
.append($('<td>', { text: email }))
$tbody.append(row)
})
})
}
$button.on('click', loadAndRender)
.click-me {
background-color: lightgrey
}
<table style="width: 100%">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button>Load and render</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
jQuery out of the box doesn't have the equivalent of a createElement. In fact the majority of jQuery's work is done internally using innerHTML over pure DOM manipulation. As Adam mentioned above this is how you can achieve similar results.
There are also plugins available that make use of the DOM over innerHTML like appendDOM, DOMEC and FlyDOM just to name a few. Performance wise the native jquery is still the most performant (mainly becasue it uses innerHTML)
What about this, for example when you want to add a <option>
element inside a <select>
$('<option/>')
.val(optionVal)
.text('some option')
.appendTo('#mySelect')
You can obviously apply to any element
$('<div/>')
.css('border-color', red)
.text('some text')
.appendTo('#parentDiv')
UPDATE
As of the latest versions of jQuery, the following method doesn't assign properties passed in the second Object
Previous answer
I feel using document.createElement('div')
together with jQuery
is faster:
$(document.createElement('div'), {
text: 'Div text',
'class': 'className'
}).appendTo('#parentDiv');
var mydiv = $('<div />') // also works