Changing element’s id
1 2 |
var mainHeading = document.getElementById('mainHeading'); mainHeading.id = 'firstHeading'; |
mainHeading is reference object. We change the property of the
reference object and it will reflect back on the page.
You can also see the results by console
1 2 |
console.log("mainHeading.id is: - "); console.log(mainHeading.id); |
result:
1 |
<h1 class='heading' id='firstHeading'> Javascript Fundamental </h1> |
getting the class names
1 |
<h2 class="heading subHeading">Part of the Front End Development learning path by Tuts+</h2> |
1 2 |
var subHeading = document.getElementsByClassName('heading')[0]; console.log(subHeading.className); |
result: heading subHeading
adding/removing a new class to an Element
subHeading.classList.add(‘special’);
You will then see the special class added to the element referenced by subHeading variable.
subHeading.classList.remove(‘special’);
Tag Name
console.log(‘mainHeading.tagName: ‘ + mainHeading.tagName); // H1
innerHTML
Contents of the elements
mainHeading.innerHTML = “” + mainHeading.innerHTML + ““;
outerHTML
Contents of the elements including the element itself.
mainHeading.outerHTML = “
” + mainHeading.innerHTML + “
“;
setAttribute
You can use methods setAttribute to
js
1 2 3 4 |
var subHeading = document.getElementsByClassName('heading')[0]; subHeading.textContent = 'I love Envato!'; subHeading.setAttribute('contenteditable', true); |
In the html you will see the attribute set in the h1 tag:
1 |
<h1 class="heading" id="mainHeading" contenteditable="true">....</h1> |
1 |
subHeading.removeAttribute('contenteditable')e; |
Does this element have attribute x ?
1 |
console.log(subHeading.hasAttribute('contenteditable')); |