Kako manipulirati DOM-om u vanilijskom JavaScript-u

Dakle, naučili ste varijable, strukture odabira i petlje. Sada je vrijeme da naučite o DOM manipulaciji i počnete raditi neke cool JavaScript projekte.

U ovom uputstvu naučit ćemo kako manipulirati DOM-om s vanilin JavaScript-om. Bez daljnjega, krenimo odmah u to.

1. Prvo najprije

Prije nego što krenemo u kodiranje, naučimo što je Dom zapravo:

Objektni model dokumenta (DOM) programsko je sučelje za HTML i XML dokumente. Predstavlja stranicu tako da programi mogu mijenjati strukturu, stil i sadržaj dokumenta. DOM predstavlja dokument kao čvorove i objekte. Na taj se način programski jezici mogu povezati na stranicu. Izvor

Uglavnom, kada preglednik učita stranicu, stvara objektni model te stranice i ispisuje je na ekranu. Objektni model predstavljen je u strukturi podataka stabla, svaki čvor je objekt sa svojstvima i metodama, a najviši čvor je objekt dokumenta.

Za pristup i izmjenu ovog objektnog modela može se koristiti programski jezik, a ta se radnja naziva DOM manipulacija. A to ćemo učiniti s JavaScriptom jer je JS sjajan.

2. Stvarni tutorial

Za tutorial će nam trebati dvije datoteke, jedna index.html, a druga manipulation.js.

  DOM Manipulation 

DOM manipulation

Tutorial

Sibling

Medium Tutorial

Out of the div

Dakle, tu je naša HTML datoteka, i kao što vidite imamo div s id-om podjele. Unutar toga imamo element h1, a u istom ćete retku shvatiti zašto kasnije imamo dva p elementa i oznaku div zatvaranja. Napokon imamo ap element s klasom teksta.

2.1. Pristup elementima

Možemo pristupiti jednom elementu ili više elemenata.

2.1.1. Pristup jednom elementu

Za pristup pojedinom elementu razmotrit ćemo dvije metode: getElementByID i querySelector.

// the method below selects the element with the id ofheadlet id = document.getElementById('head');
// the code below selects the first p element inside the first divlet q = document.querySelector('div p');
/* Extra code */// this changes the color to redid.style.color = 'red';// give a font size of 30pxq.style.fontSize = '30px';

Sada smo pristupili dvama elementima, elementu h1 s id-om glave i prvom p elementu unutar div-a.

getElementById uzima kao argument id, a querySelector uzima kao argument CSS selektor i vraća prvi element koji odgovara selektoru. Kao što vidite, ishod metoda dodijelio sam varijablama, a zatim sam na kraju dodao malo stylinga.

2.1.2. Pristup višestrukim elementima

Pri pristupu više elemenata vraća se popis čvorova. Nije niz, ali djeluje kao jedan. Tako ga možete petljati i koristiti svojstvo length da biste dobili veličinu popisa čvorova. Ako želite dobiti određeni element, možete upotrijebiti zapis niza ili metodu predmeta. Vidjet ćete ih u kodu.

Za pristup višestrukim elementima koristit ćemo tri metode: getElementsByClassName, getElementsByTagName i querySelectorAll.

// gets every element with the class of textlet className = document.getElementsByClassName('text');
// prints the node listconsole.log(className);
/* prints the third element from the node list using array notation */console.log(className[2]);
/* prints the third element from the node list using the item function */console.log(className.item(2));
let tagName = document.getElementsByTagName('p');let selector = document.querySelectorAll('div p');

Čini se da je kôd sam po sebi razumljiv, ali svejedno ću ga objasniti jer sam fin tip. :)

Prvo koristimo getElementsByClassName koji kao argument uzima ime klase. Vraća popis čvorova sa svakim elementom koji ima tekst kao klasu. Zatim ispisujemo popis čvorova na konzoli. Također ispisujemo treći element s popisa pomoću oznake niza i metode predmeta .

Drugo, odabiremo svaki p element pomoću metode getElementsByTagName koja uzima ime oznake kao argument i vraća popis čvorova tog elementa.

Konačno, koristimo metodu querySelectorAll koja uzima kao argument CSS selektor. U ovom je slučaju potreban div p, tako da će vratiti popis čvorova s p elemenata unutar div-a.

Kao vježbu ispišite sve elemente s popisa tagName i popisa čvora selektora i saznajte njihovu veličinu.

2.2. Prelazak DOM-a

Do sada smo pronašli način pristupa određenim elementima. Što ako želimo pristupiti elementu pored elementa kojem smo već pristupili ili pristupiti nadređenom čvoru prethodno pristupanog elementa? Svojstva firstChild, lastChild, parentNode, nextSibling i previousSibling mogu ovaj posao obaviti umjesto nas.

firstChild koristi se za dobivanje prvog podređenog elementa čvora. lastChild , kao što pretpostavljate, dobiva zadnji podređeni element čvora. nadređeni čvor jekoristi se za pristup nadređenom čvoru elementa. nextSibling za nas dobiva element pored elementa kojem smo već pristupili, a previousSibling dobiva element koji je prethodio elementu kojem smo već pristupili.

// gets first child of the element with the id of divisionlet fChild = document.getElementById('division').firstChild;console.log(fChild);
// gets the last element from element with the id of divisionlet lChild = document.querySelector('#division').lastChild;
// gets the parent node of the element with the id divisionlet parent = document.querySElector('#division').parentNode;console.log(parent);
// selects the element with the id of middlelet middle = document.getElementById('middle');// prints ond the console the next sibling of middleconsole.log(middle.nextSibling);

Gornji kod prvo dobiva element firstChild elementa s id-om podjele, a zatim ga ispisuje na konzoli. Tada dobiva element lastChild iz istog elementa s id-om podjele. Tada dobiva roditeljski čvor elementa s id-om podjele i ispisuje ga na konzoli. Konačno, odabire element s id-om sredine i ispisuje njegov nextSibling čvor.

Most browsers treat white spaces between elements as text nodes, which makes these properties work differently in different browsers.

2.3. Get and Updating element content

2.3.1. Setting and getting text Content

We can get or set the text content of elements. To achieve this task we are going to use two properties: nodeValue and textContent.

nodeValue is used to set or get the text content of a text node. textContent is used to set or get the text of a containing element.

// get text with nodeValuelet nodeValue = document.getElementById('middle').firstChild.nodeValue;console.log(nodeValue);
// set text with nodeValuedocument.getElementById('middle').firstChild.nodeValue = "nodeValue text";
// get text with textContentlet textContent = document.querySelectorAll('.text')[1].textContent;console.log(textContent);
// set text with textContentdocument.querySelectorAll('.text')[1].textContent = 'new textContent set';

Did you notice the difference between nodeValue and textContent?

If you look carefully at the code above, you will see that for us to get or set the text with nodeValue, we first had to select the text node. First, we got the element with the middle id, then we got its firstChild which is the text node, then we got the nodeValue which returned the word Tutorial.

Now with textContent, there is no need to select the text node, we just got the element and then we got its textContent, either to set and get the text.

2.3.2. Adding and Removing HTML content

You can add and remove HTML content in the DOM. For that, we are going to look at three methods and one property.

Let’s start with the innerHTML property because it is the easiest way of adding and removing HTML content. innerHTML can either be used to get or set HTML content. But be careful when using innerHTML to set HTML content, because it removes the HTML content that is inside the element and adds the new one.

document.getElementById('division').innerHTML =`
      
  • Angular
  • Vue
  • React
`;

If you run the code, you will notice that everything else in the div with the id of division will disappear, and the list will be added.

We can use the methods: createElement(), createTextNode(), and appendChild() to solve this problem.

createElement is used to create a new HTML element. creatTextNode used to create a text node, and appendChild is used to append a new element into a parent element.

//first we create a new p element using the creatElementlet newElement = document.createElement('p');/* then we create a new text node and append the text node to the element created*/let text = document.createTextNode('Text Added!');newElement.appendChild(text);
/* then we append the new element with the text node into the div with the id division.*/document.getElementById('division').appendChild(newElement);

There is also a method called removeChild used to remove HTML elements.

// first we get the element we want to removelet toBeRemoved = document.getElementById('head');// then we get the parent node, using the parentNOde propertylet parent = toBeRemoved.parentNode;/* then we use the removeChild method, with the element to be removed as a parameter.*/parent.removeChild(toBeRemoved);

So first we get the element that we want to remove, and then we get its parent node. Then we called the method removeChild to remove the element.

2.4. Attribute node

Now we know how to handle elements, so let’s learn how to handle the attributes of these elements. There are some methods like GetAttribute, setAttribute, hasAttribute, removeAttribute, and some properties like className and id.

getAttribute as its name may suggest, it is used to get an attribute. Like the class name, the id name, the href of a link or any other HTML attribute.

setAttribute is used to set a new attribute to an element. It takes two arguments, first the attribute and second the name of the attribute.

hasAttribute used to check if an attribute exists, takes an attribute as an argument.

removeAttribute used to remove an attribute, it takes an attribute as an argument.

Id this property is used to set or get the id of an element.

ClassName is used to set or get the class of an element.

// selects the first divlet d = document.querySelector('div');// checks if it has an id attribute, returns true/falseconsole.log('checks id: '+d.hasAttribute('id'));// set a new class attributed.setAttribute('class','newClass');// returns the class nameconsole.log(d.className);

I know I am a good dude, but that code is just self-explanatory.

Conclusion

That is it! We have learned so many concepts, but there is more to learn about DOM manipulation. What we have covered here gives you a good foundation.

Go ahead and practice, and create something new to cement this new knowledge.

Good day, good coding.