no-jquery 02 DOM

时间:2023-03-08 18:37:23

DOM Manipulation

Creating Elements

// IE 5.5+
document.createElement('div');

Inserting Elements Before & After

// IE 4+
document.getElementById('1')
.insertAdjacentHTML('afterend', '<div id="1.1"></div>'); // IE 4+
document.getElementById('1')
.insertAdjacentHTML('beforebegin', '<div id="0.9"></div>');

Inserting Elements As Children

// IE 4+
document.getElementById('parent')
.insertAdjacentHTML('afterbegin', '<div id="newChild"></div>'); // IE 4+
document.getElementById('parent')
.insertAdjacentHTML('beforeend', '<div id="newChild"></div>')

Moving Elements

// IE 5.5+
document.getElementById('parent')
.appendChild(document.getElementById('orphan')); // IE 5.5+
document.getElementById('parent')
.insertBefore(document.getElementById('orphan'), document.getElementById('c1'));

Removing Elements

// IE 5.5+
document.getElementById('foobar').parentNode
.removeChild(document.getElementById('foobar'));

Adding & Removing CSS Classes

// All modern browsers, with the exception of IE9
document.getElementById('foo').classList.add('bold'); // All browsers
document.getElementById('foo').className += 'bold'; // All modern browsers, with the exception of IE9
document.getElementById('foo').classList.remove('bold'); // All browsers
document.getElementById('foo').className =
document.getElementById('foo').className.replace(/^bold$/, '');

Adding/Removing/Changing Attributes

// IE 5.5+
document.getElementById('foo').setAttribute('role', 'button'); // IE 5.5+
document.getElementById('foo').removeAttribute('role');

Adding & Changing Text Content

// IE 5.5+
document.getElementById('foo').innerHTML = 'Goodbye!'; // IE 5.5+ but NOT Firefox
document.getElementById('foo').innerText = 'GoodBye!'; // IE 9+
document.getElementById('foo').textContent = 'Goodbye!';

Adding/Updating Element Styles

// IE 5.5+
document.getElementById('note').style.fontWeight = 'bold';