Introduction
In this article, I tried to collect JavaScript code snippets (eng. code snippets), which can be useful in everyday work with DOM. Almost all snippets are written in two versions, using only plain JavaScript or with the help of the jQuery library.

Document Ready
The following examples show an “event listener” that waits for the moment when the DOM is loaded so that JavaScript can manipulate it. The same would be obtained if the JavaScript code were placed at the end of the body, i.e. before the closing “body” tag itself.
|
1 2 3 |
document.addEventListener("DOMContentLoaded", function() { // some code }, false); |
|
1 2 3 |
$(document).ready(function() { // some code }); |
|
1 2 3 |
jQuery(document).ready(function ($) { // some code }); |
Document Load
The load event is “triggered” only when the entire page with all CSS styles, images…
is loaded
|
1 2 3 |
window.addEventListener("load", function(event) { console.log("All resources finished loading!"); }); |
|
1 2 3 |
$(window).on('load', function(){ console.log("All resources finished loading!"); }); |
Selecting DOM elements
Selection via CSS selector
HTML
|
1 2 3 4 5 6 7 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> |
JavaScript
Select all elements that satisfy the selector
|
1 |
document.querySelectorAll("CSSselektor"); |
Example
|
1 2 3 4 5 6 |
var elementi =document.querySelectorAll('#parent p'); // Returns: "Array like" object var nizElemenata = Array.prototype.slice.call(elementi); // Cast to array nizElemenata.forEach(function(current, index){ console.log(current); }); |
Selecting only the first element that satisfies the selector
If we want to return with plain JS only the first element that satisfies the selector criteria, we can use:
|
1 |
document.querySelector('selector'); |
Syntax for older browsers
If there is a need to satisfy browsers older than IE 11, then the following JS selectors should be used:
|
1 2 3 4 5 6 7 8 |
// to select an element via class: document.getElementsByClassName('foo'); // for selecting the tag element document.getElementsByTagName('a'); // for selecting an element via the ID attribute document.getElementById('foo'); |
|
1 |
$("CSSselector"); |
Example
|
1 2 3 4 5 6 |
var elementi =$("p"); // Returnsobjekat var nizElemenata = Array.prototype.slice.call(elementi); // Cast to array nizElemenata.forEach(function(current, index){ console.log(current); }); |
Select parent
HTML
|
1 2 3 4 5 6 7 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> |
JavaScript
|
1 |
document.querySelector('#izabrani').parentNode; // Returns the HTML element that is the "parent" of the selected element |
|
1 |
$("#izabrani").parent(); |
Selecting all children
HTML
|
1 2 3 4 5 6 7 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> |
JavaScript
The following statements return an array of elements with all children of the selected selector. In the following examples, it is necessary to select all li elements:
|
1 |
document.querySelector('#parent').children; // Returns an "Array like" object whose properties are all the HTML elements that are its children |
|
1 |
document.querySelector('#parent').childNodes; |
NOTE:
It should be emphasized that “childNodes” returns as a child element even an empty space between HTML tags (as an empty text node)
|
1 |
$('#parent').children(); // Returns a jQuery object whose properties are all the HTML elements that are its children |
Selecting the first child
HTML
|
1 2 3 4 5 6 7 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> |
JavaScript
If you want it to be the first child then the following commands can be used:
|
1 |
document.querySelector('#parent').firstElementChild; |
|
1 |
document.querySelector('#parent').firstChild; |
NOTE:
If there is an empty space between the parent tag and the first element that is its child, it will not return that element but an EMPTY text node.
|
1 |
$('#parent').children().first(); // Returns |
Selecting the last child
HTML
|
1 2 3 4 5 6 7 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> |
JavaScript
|
1 |
document.querySelector('#parent').lastElementChild; |
|
1 |
document.querySelector('#parent').lastChild; |
NOTE:
If there is an empty space between the parent tag and the last element that is its child, it will not return that element but an EMPTY text node.
|
1 |
$('#parent').children().last(); |
Selecting a previous relative
HTML
|
1 2 3 4 5 6 7 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> |
JavaScript
|
1 |
document.querySelector("#izabrani").previousElementSibling; // Returnsparagraf id="prviParagraf" |
|
1 |
document.querySelector("#izabrani").previousSibling; |
NOTE:
If there is an empty space between the parent tag and the last element that is its child, it will not return that element but an EMPTY text node.
|
1 |
$("#izabrani").prev(); // Returnsparagraf id="prviParagraf" |
Selecting the next relative
HTML
|
1 2 3 4 5 6 7 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> |
JavaScript
|
1 |
document.querySelector("#izabrani").nextElementSibling; // Returnsparagraf id="drugiParagraf" |
|
1 |
document.querySelector("#izabrani").nextSibling; |
NOTE:
If there is an empty space between the parent tag and the last element that is its child, it will not return that element but an EMPTY text node.
|
1 |
$("#izabrani").next(); // Returnsparagraf id="drugiParagraf" |
Selecting all relatives
HTML
|
1 2 3 4 5 6 7 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> |
JavaScript
In this example, the function findRelatives creates a new array from the children of parents that satisfy the condition. Adds elements to the array if there is no filter or if the filter returns an element, as long as there is a next relative.
|
1 2 3 4 5 6 7 8 9 10 11 |
function nadjiRodjake(el) { var nizRodjaci = []; el = el.parentNode.firstElementChild; do { nizRodjaci.push(el); } while (el = el.nextElementSibling); return nizRodjaci; } var izabrani = document.querySelector('#izabrani'); var sviRodjaci = nadjiRodjake(izabrani); // Returnsniz sa svim rodjacima trazenog elementa |
|
1 |
$("#izabrani").siblings(); |
Filtering selected elements
Reducing elements that satisfy the targeted selector if they “pass” the filter test. The filter test can be another selector, and most often the filter is the function:
HTML
|
1 2 3 4 5 6 7 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> |
JavaScript
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function filtrirajRodjake(el, filterTag) { var nizRodjaci = []; var el = el.parentNode.firstElementChild; var proveraElemenata = function (el, filterTag) { return el.nodeName.toLowerCase() == filterTag; // Returns: TRUE ili FALSE } do { if (!proveraElemenata || proveraElemenata(el,filterTag)){ // Inserts e. which satisfy the check in sequence nizRodjaci.push(el); } } while (el = el.nextElementSibling); return nizRodjaci; } var izabrani = document.querySelector('#izabrani'); var filtriraniRodjaci = filtrirajRodjake(izabrani, "span"); // Returns: sve <span> rodjake |
|
1 2 3 |
$( "span" ) .filter( "#izabrani" ) .css( "background", "red" ); |
or using the function
|
1 2 3 4 5 |
$( "span" ) .filter(function( indexElementaNiza ) { return $( this ).attr( "id" ) === "izabrani"; }) .css( "background", "red" ); |
Manipulation of DOM elements
Creating an element
|
1 |
var el = document.createElement('div'); |
|
1 |
var el = $('div'); |
Adding an element as a child
Adding a new element as the last child of each selected element.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
//Element kome se dodaje novi element var roditelj = document.querySelector('#parent'); // Creating a new element var newDiv = document.createElement('div'); var newP = document.createElement('p'); var newText = document.createTextNode('Hello World!'); // adding elements as a child newP.appendChild(newText); newDiv.appendChild(newP); roditelj.appendChild(newDiv); |
|
1 2 3 4 5 |
//Element kome se dodaje novi element var roditelj = document.querySelector('#parent'); // adding new content as a child roditelj.innerHTML += '<div><p>Hello World!</p></div>'; |
NOTE:
Please note that the addition and assignment operator “+=” is used with innerHTML, because if only the assignment operator “=” is used, then when changing the DOM, all elements inside the “parent” element are stepped on and a new modified DOM is created, and if there are Event handlers that were attached to the “old DOM”, now NO THERE ARE!
I variant
|
1 2 3 4 5 6 7 8 9 10 11 12 |
//Element kome se dodaje novi element var roditelj = $('#parent'); // Creating a new element var newDiv = $('<div>'); var newP = $('<p>'); var newText = $.parseHTML('Hello World!'); // adding elements as a child newP.append(newText); newDiv.append(newP); roditelj.append(<div>); |
II variant:
|
1 |
$('#parent').append("<div><p>Hello World!</p></div>") |
Clone element
|
1 2 3 4 5 |
var el = document.querySelector('#izabrani'); var roditelj = document.querySelector('#parent'); var klon = el.cloneNode(true); roditelj.appendChild(klon); |
If the parameter is “true”, a “deep copy” is made, i.e. copy with all attributes and “child” elements, while if “false” is selected it is copied without “child” elements.
|
1 2 |
var izabrani = $( "#izabrani" ).clone(); izabrani.appendTo( "#parent" ); |
Add before element
|
1 |
var insertedNode = parentNode.insertBefore(newNode, referenceNode); |
If referenceNode is null then it is inserted at the end of the list of all childNodes (same as appendChild).
Example of adding an element to a list
|
1 2 3 4 5 6 7 8 |
var noviElement = document.createElement("p"); var tekstElementa = document.createTextNode("Tekst unutar novog elementa"); noviElement.appendChild(tekstElementa); var roditelj = document.getElementById("parent"); var refElement = roditelj.children[2]; roditelj.insertBefore(noviElement, refElement); // Inserts a new element before the span with id="selected" |
|
1 2 |
// Add something before the selected element $('#izabrani').before("<div>Hello World!</div>"); |
|
1 2 |
// Add something before the selected element $("<div>Hello World!</div>").insertBefore('#izabrani'); |
Adding after element
Although there is an insertBefore in JavaScript, there is NOT an insertAfter, so it is necessary to resort to a “cunning”:
|
1 2 3 |
function insertAfter(el, referenceNode) { referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling); } |
Example of adding an element to a list
|
1 2 3 4 5 |
var noviElement = document.createElement('div'); noviElement.innerHTML = '<p>Hello World!</p>'; var refNode = document.querySelector('div.before'); insertAfter(noviElement, refNode); |
|
1 2 |
// Add something after the selected element $("<div>Hello World!</div>").insertAfter('#izabrani'); |
|
1 2 |
// Add something after the selected element $('#izabrani').after("<div>Hello World!</div>"); |
Deleting an element
|
1 2 |
var izabrani = document.querySelector("#izabrani"); izabrani.parentNode.removeChild(izabrani); |
|
1 |
$('span').remove(); |
Deletes ALL span elements
|
1 |
$('span').remove('#izabrani'); |
Deletes only span elements with ID=”selected”
Deleting all children of an element
|
1 2 |
var el = document.querySelector('#izabrani'); el.innerHTML = ''; |
|
1 |
$( "#izabrani" ).empty(); |
Wrapping an element with an element
HTML
|
1 |
<span id="izabrani">Tekst u izabranom span-u</span> |
JavaScript
|
1 2 3 4 5 6 7 |
Array.prototype.forEach.call(document.querySelectorAll('#izabrani'), (el) => { const obavijajuciDiv = document.createElement('div'); obavijajuciDiv.className = 'omotac'; el.parentNode.insertBefore(obavijajuciDiv, el); el.parentNode.removeChild(el); obavijajuciDiv.appendChild(el); }); |
|
1 |
$('#izabrani').wrap('<div class="omotac"></div>'); |
Result
|
1 2 3 |
<div class="omotac"> <span id="izabrani">3. Tekst u izabranom span-u </span> </div> |
Replacing an element with another
HTML
|
1 |
<span id="izabrani">Tekst u izabranom span-u</span> |
JavaScript
|
1 |
el.parentNode.replaceChild(newEl, el) |
Example
|
1 2 3 4 5 6 7 8 9 |
// Selection of the element to be replaced var el = document.querySelector('#izabrani'); // Creating a new element to take its place var newEl = document.createElement('p'); newEl.innerHTML = '<strong>Hello World!</strong>'; //Zamena elemenata: el.parentNode.replaceChild(newEl, el); |
|
1 |
$('#izabrani').replaceWith('<p><strong>Hello World!</strong></p>'); |
Checking if selector (is) exists
|
1 2 |
var el = document.querySelector('p'); el.matches('#izabrani'); |
|
1 |
$(li).is(":first-child"); |
Example
In the following snippets a boolean value is obtained, therefore if the answer is “true” then they are equal selectors. Mostly used with “if”.
|
1 2 3 4 5 6 7 8 9 |
$("li").click(function () { if ($(this).is(":first-child")) { $("p").text("This is list item 1"); } else if ($(this).is(".middle")) { $("p").text("This is middle class list"); } else if ($(this).is(":contains('item 5')")) { $("p").text("It's 5th list"); } }); |
Working with DOM content
Getting the content (text) inside the element
|
1 2 3 |
<div id="parent"> <span id="prviSpan">Tekst <strong>u prvom</strong> span-u </span> </div> |
The following snippets return the text of the specified element:
|
1 2 3 4 5 6 7 8 9 10 11 |
var el = document.getElementById("prviSpan"); // Returns only text (ignores HTML formatting eg<strong>) and is quite fast var tekst = el.textContent; // Returns: The text in the first span // Returnstekst sa HTML tagovima (malo je sporije jer mora da parsira HTML) var tekst = el.innerHTML; // Returns: The text <strong>in the first</strong> span // Returnstext but CSS affects the output (if visibility: hidden does not show the text), // uveo je IE i nije standardizovano sa W3C pa nije bas preporucljivo var tekst = el.innerText; |
|
1 2 3 4 5 6 7 |
var el = $("#prviSpan"); // Returnssamo tekst var text = el.text(); // Returns: The text in the first span // Returnstekst sa HTML tagovima var text = el.html() // Returns: The text <strong>in the first</strong> span |
Inserting or replacing content (text) within an element
|
1 2 3 |
<div id="parent"> <span id="prviSpan">Tekst <strong>u prvom</strong> span-u </span> </div> |
The following snippets replace the existing text with new:
|
1 2 3 4 5 6 7 8 9 10 11 |
var el = document.getElementById("prviSpan"); // Inserts and modifies existing text el.textContent= "Novi tekst"; // Inserts text even with HTML (slightly slower because it parses HTML) el.innerHTML= "Novi <strong>tekst</strong>"; // Inserts text even if CSS affects the output (if visibility: hidden does not show the text), // uveo je IE i nije standardizovano sa W3C pa nije bas preporucljivo el.innerText= "Novi tekst"; |
|
1 2 3 4 5 6 7 |
var el = $("#prviSpan"); // Inserts and modifies overlapping text el.text("Novi tekst"); // Inserts text even with HTML el.html("Novi <strong>tekst</strong>"); |
outerHTML element
HTML
|
1 2 3 4 5 6 7 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> |
JavaScript
For the HTML presentation of the selected element, we use:
|
1 2 |
var outerHTML = document.querySelector("#izabrani").outerHTML; console.log(outerHTML); // Returns: "<span id='izabrani'>Tekst u izabranom span-u</span>" |
One of the few cases where jQuery doesn’t have a direct method for a problem that Plain JS does, so it’s solved in a roundabout way (in a “temporary div element clones our element”).
|
1 |
console.log($('<div>').append($("#izabrani").clone()).html()); // Returns"<span id='izabrani'>Tekst u izabranom span-u</span>" |
Value inside “input” or “textarea”
|
1 |
document.querySelector('#nekiInput').value; |
Example
|
1 2 |
<input id="text input" value="initial value" type="text" /> <p id="printing"></p> |
JavaScript
|
1 2 3 4 5 6 7 8 9 |
var elUnos = document.querySelector("#text-input"); var ispis = document.querySelector("#print"); var pocetnaVrednost = elUnos.value; ispis.textContent= pocetnaVrednost; elUnos.addEventListener("keyup", function(){ var vrednostUnosa = elUnos.value ; ispis.textContent= vrednostUnosa; }, false); |
|
1 |
$('selectori').val(); |
Example
|
1 2 |
<input id="text input" value="initial value" type="text" /> <p id="printing"></p> |
JavaScript
|
1 2 3 4 5 6 7 |
// Getting the input value and printing it in a paragraph with id="print" $( "#text-input" ) .keyup(); // An event trigger that buys the default value of the input .keyup(function() { var value = $( this ).val(); $( "#print" ).text( value ); }) |
Radio input
HTML
|
1 2 3 4 5 6 |
<form id="radioForm"> <label>Prvi izbor: <input type="radio" name="radioBtn" value="Prvi" /></label> <label>Drugi izbor: <input type="radio" name="radioBtn" value="Drugi"/></label> <label>Treci izbor: <input type="radio" name="radioBtn" value="Treci" /></label> <label>Cetvrti izbor: <input type="radio" name="radioBtn" value="Cetvrti" /></label> </form> |
JavaScript
|
1 2 3 4 5 6 7 8 9 10 |
var elRadioInput = document.forms['radioForm'].elements['radioBtn']; var len = elRadioInput.length; for (var i=0; i <= len; i++) { elRadioInput[i].onclick = function(e) { var indexRadioBtn = Array.prototype.indexOf.call(elRadioInput, e.currentTarget) +1; // "this.value" can be used instead of "e.currentTarget.value" var value = e.currentTarget.value; console.log("He was selected" + indexRadioBtn + ' radioBtn ' + "whose value is" + value); }; } |
|
1 2 3 4 5 6 7 8 9 10 |
var elRadioInput = $('#radioForm input'); var len = elRadioInput.length; for (var i=0; i <= len; i++) { elRadioInput[i].onclick = function(e) { var indexRadioBtn = elRadioInput.index(e.currentTarget) + 1; // "this.value" can be used instead of "e.currentTarget.value" var value = e.currentTarget.value; console.log("He was selected" + indexRadioBtn + ' radioBtn' + "whose value is" + value); }; } |
Select
HTML
|
1 2 3 4 5 |
<select id="pozicija"> <option value="direktor">Direktor</option> <option value="poslovodja">Poslovodja</option> <option value="radnik">Radnik</option> </select> |
JavaScript
|
1 2 3 4 5 6 7 |
var select = document.getElementById("pozicija"); var izborPozicije = "direktor"; select.addEventListener("change", function(){ izborPozicije = select.options[select.selectedIndex].value; console.log(izborPozicije); }) |
|
1 2 3 4 5 6 |
var izborPozicije = "direktor"; $("#pozicija").change(function(){ izborPozicije = $("#pozicija option:selected").val(); console.log(izborPozicije); }) |
Working with HTML attributes
GettingHTML attribute values
Attributes: href, title, alt, and value have their own “private” access property, so they can be easily accessed directly through them:
|
1 2 3 |
var unos = document.querySelector('selector').value; var link = document.querySelector('selector').href; // Returns: full path http://example.com/deo/clanak.html var title = document.querySelector('selector').title; |
HTML
|
1 2 3 |
<form> <input type="checkbox" name="vehicle" value="Bike" checked> I have a bike<br> </form> |
Other attributes that do not have their own “personal” method can be accessed as follows:
|
1 |
el.getAttribute('name'); // Returns the value of the "vehicle" attribute |
|
1 |
$('input').attr('name'); // Returnsvrednost "vehicle" |
Getting the value of the DATA attribute
I must mention that this data can be obtained easily and in the previous way as a regular HTML attribute.
NOTE:
Do not use capital letters in the names of data attributes, but use dashes in between!
HTML
|
1 |
<p class="person" data-index-no="123">Pera Perić</p> |
JavaScript
|
1 2 3 4 5 6 7 |
var el = document.querySelector('.person'); el.getAttribute('data-index-no'); // For E11+ the newer command can be used but with camelCase because it doesn't support hyphens!: el.dataset['indexNo']; ili var b = el.dataset.indexNo; |
NOTE:
Use camelCase when calling as part of “dataset” syntax!
|
1 2 3 |
$('.person').data('index-no'); // the same effect is obtained when we use cameCase instead of a hyphen $('.person').data('indexNo') |
Setting attribute values
Attributes: href, title, alt, and value have their own “private” access property, so they can be easily accessed directly through them:
|
1 2 3 |
document.querySelector('selector').value = "some input"; document.querySelector('selector').href = "var link = document.querySelector('selector').href = "; document.querySelector('selector').title="This is the title"; |
HTML
|
1 2 3 |
<form> <input type="checkbox" name="vehicle" value="Bike" checked> I have a bike<br> </form> |
JavaScript
|
1 2 |
var el = document.querySelector('#text-input'); el.setAttribute('name', 'input-polje'); |
|
1 |
$('#text-input').attr('name', 'input-polje'); |
NOTE:
Added attributes are not physically visible in the DOM, but are stored in memory.
Checking if the element has a class
|
1 |
el.classList.contains(className); |
NOTE:
The classList object is not supported by IE for versions less than IE10
|
1 |
$el.hasClass(className); |
Adding a class to an element
|
1 |
el.classList.add(className); |
NOTE:
The classList object is not supported by IE for versions less than IE10
|
1 |
$el.addClass(className); |
Remove class
|
1 |
el.classList.remove(className); |
NOTE:
This classList object is not supported by IE for versions less than IE10
|
1 |
$el.removeClass(className); |
Alternate addition and deletion of class (togle)
HTML
|
1 2 3 4 5 6 7 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> |
JavaScript
No toggle()
See the Pen Toogle plainJS by Web programming (@chos) onCodePen.
From that()
|
1 |
el.classList.toggle("className"); |
NOTE:
This method is not supported in IE (see compatibility table here)
Example
|
1 2 3 4 |
var el = document.getElementById('prviSpan'); el.onclick = function () { el.classList.toggle("classname"); } |
Mix
Or mix the previous two examples
See the Pen EvaKoN by Web programming (@chos) on CodePen.
|
1 |
$el.toggleClass("classname"); |
Example
|
1 2 3 |
$("#prviSpan").on("click", function(){ $("#prviSpan").toggleClass("classname"); }); |
Element styling
Getting element properties
Since the “getComputedStyle()” method returns the values of all properties in the form of “CSSStyleDeclaration” objects, it is also necessary to use the getPropertyValue method:
|
1 |
window.getComputedStyle(el,null).getPropertyValue("CSSsvojstvo") |
Example
|
1 2 3 4 |
var el = document.getElementById('izabrani'); var styleValue = window.getComputedStyle(el,null).getPropertyValue("font-size"); console.log(styleValue); // Returnsvrednost uvek u px |
|
1 |
$(el).css("CSSsvojstvo"); // Returnsvrednost CSS svojstva |
Example
|
1 2 3 |
var el = $("#izabrani"); var styleValue = el.css("fontSize"); // Returnsvrednost console.log(styleValue); // Returnsvrednost uvek u px |
Defining CSS properties for an element
Defining a single property
|
1 |
el.style.CSSsvosjstvo = "value"; |
Example
|
1 2 |
var el = document.getElementById('izabrani'); el.style.fontSize = "50px"; |
Defining multiple properties at once
|
1 2 3 4 |
function css(el, styles) { for (var property in styles) el.style[property] = styles[property]; } |
Example
|
1 2 |
var el = document.getElementById('izabrani'); css(el, { background: 'red', 'font-size': '25px' }); |
Defining property values
|
1 |
$('#izabrani').css("display", "block"); // Defines the value property |
Defining multiple properties at once
|
1 2 3 4 |
$('#izabrani').css({ "font-size" : "25px", "background" : "red" }); |
Show, hide and toggle
NOTE:
Methods show() and toggle() require another attribute which can be: “block”, “flex” “inline-block”, “inline” …
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function hide(el) { el.style.display = 'none'; } function show(el, vrednostDisplay) { el.style.display = vrednostDisplay || "block"; } function toggle(el, vrednostDisplay) { var display = (window.getComputedStyle ? getComputedStyle(el, null) : el.currentStyle).display; if (display == 'none') el.style.display = vrednostDisplay || "block";; else el.style.display = 'none'; } |
Example
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> <button id="btn">Toggle</button> <script> var el = document.querySelector("#izabrani"); var btn =document.querySelector("#btn"); btn.addEventListener("click", function(){ toggle(el, "block"); }) </script> |
|
1 2 3 |
$( "#izabrani" ).show() $( "#izabrani" ).hide(); $( "#izabrani" ).toggle(); |
NOTE:
All three methods have “built-in” animation. If we want animation, it is enough to pass the attribute to the function that defines the duration of the animation. With these methods, width, height, and opacity are animated simultaneously. It is also possible to change the default animation type “swing” with another attribute.
Example
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div id="parent"> <span id="prviSpan">Tekst u prvom span-u</span> <p id="prviParafraf">Tekst u prvom "p" tag-u</p> <span id="izabrani">Tekst u izabranom span-u</span> <p id="drugiParafraf">Tekst u drugom "p" tag-u</p> <span id="drugiSpan">Tekst u drugom spanu</span> </div> <button id="btn">Toggle</button> <script> var btn = document.querySelector("#btn"); btn.addEventListener("click", function(){ $( "#izabrani" ).toggle(1000); }) </script> |
Element position
Element height and width
Box with padding and border
|
1 2 3 4 5 |
var box = document.querySelector('#izabrani'); var width = box.offsetWidth; var height = box.offsetHeight; console.log(width, height); |
Similar can be obtained with getBoundingClientRect() method (supported >=IE9)
|
1 2 3 |
var obj = document.querySelector('#izabrani'); var rect = obj.getBoundingClientRect(); console.log(rect.width, rect.height); |
Box with podding, border and margin
|
1 2 3 4 5 6 7 8 9 |
function outerWidth(el) { var width = el.offsetWidth; var style = getComputedStyle(el); width += parseInt(style.marginLeft) + parseInt(style.marginRight); return width; } outerWidth(el); |
Box without border
|
1 2 3 4 5 |
var box = document.querySelector('#izabrani'); var widthNoBorder = box.clientWidth; var heightNoBorder = box.clientHeight; console.log(widthNoBorder, heightNoBorder); |
Box with padding and border
|
1 2 3 4 5 |
var box = $('#izabrani'); var width = box.outerWidth(); var height = box.outerHeight(); console.log(width, height); |
Box with podding, border and margin
|
1 2 3 4 5 |
var box = $('#izabrani'); var width = box.outerWidth(true); var height = box.outerHeight(true); console.log(width, height); |
Box without border
|
1 2 3 4 5 |
var box = $('#izabrani'); var widthNoBorder = box.innerWidth(); var heightNoBorder = box.innerHeight(); console.log(widthNoBorder, heightNoBorder); |
Distance of element to parent
The value from the edge of the selected element to the edge of the first “non-static” parent (one that does not have the position:”static” property). The left and upper edge of the element is observed.
|
1 2 3 |
var el = document.querySelector('#izabrani'); var doLeveIviceRoditelje = el.offsetLeft; var doGornjeIviceRoditelje = el.offsetTop |
|
1 2 3 |
var el = $('#izabrani'); var doLeveIviceRoditelje = el.position().left; var doGornjeIviceRoditelje = el.position().top; |
Distance of the element to the document
|
1 2 3 4 5 6 7 8 |
function offset(el) { var rectLeft = el.getBoundingClientRect().left, var rectTop = el.getBoundingClientRect().top, scrollLeft = window.pageXOffset || document.documentElement.scrollLeft, scrollTop = window.pageYOffset || document.documentElement.scrollTop; return { top: rectTop + scrollTop, left: rectLeft + scrollLeft } } |
Example
|
1 2 3 |
var izabrani = document.querySelector('#izabrani'); var rastojanje = offset(izabrani); console.log(rastojanje.left, rastojanje.top); |
Similar can be obtained with the getBoundingClientRect() method:
|
1 2 3 |
var obj = document.querySelector('#izabrani'); var rect = obj.getBoundingClientRect(); console.log(rect.left, rect.top, rect.right, rect.bottom); |
|
1 2 3 |
var izabrani = $('#izabrani'); var rastojanje = izabrani.offset(); console.log(rastojanje.left, rastojanje.top); |
Checking element visibility in viewport
With the following snippet, we check whether the selected element is entirely visible in the viewport.
|
1 2 3 4 5 6 7 8 9 10 |
function isInViewport(element) { var rect = element.getBoundingClientRect(); var html = document.documentElement; return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || html.clientHeight) && rect.right <= (window.innerWidth || html.clientWidth) ); } // ReturnsTRUE ili FALSE |
Example
|
1 2 |
var img = document.querySelector('img'); isInViewport(img); // Returns"true" ako je ceo element u viewport-u |
Scroll
The method that returns a value for how much the viewport of an element is scrolled is:
|
1 |
el.scrollTop; |
For window/document we can also use:
- window.pageYOffset – not supported by version < IE9
- window.scrollY – no support for IE
- document.documentElement.scrollTop
But in order to achieve the greatest possible cross-browser compatibility, it is good to use the following expression:
|
1 |
var vrednostScrolla = window.pageYOffset || document.documentElement.scrollTop || body.scrollTop || 0; |
See the Pen JS scroll by Web programming (@chos) on CodePen.
The method that returns a value for how much the viewport of an element is scrolled is:
|
1 |
el.scrollTop(); |
See the Pen jQuery scroll by Webprogramming (@chos) on CodePen.
Mouse position at click event
|
1 2 3 4 5 6 |
document.addEventListener('click', function (e) { e = e || window.event; var pageX = e.pageX; var pageY = e.pageY; console.log(pageX, pageY); }); |
|
1 2 3 4 5 6 |
$("body").click(function(e){ var parentOffset = $(this).parent().offset(); var relX = e.pageX - parentOffset.left; var relY = e.pageY - parentOffset.top; console.log(relX, relY); }); |
If some other element is selected instead of the body tag, we will get a relative position in relation to it

