Skip to content

Instantly share code, notes, and snippets.

@kuroisuna
Last active September 22, 2016 15:44
Show Gist options
  • Save kuroisuna/7d313ac4e12037cdd2185cb51be0ad4b to your computer and use it in GitHub Desktop.
Save kuroisuna/7d313ac4e12037cdd2185cb51be0ad4b to your computer and use it in GitHub Desktop.
JS: Get node properties and values with vanilla javascript
// If we need the value of some form items
// Retrieve the form by its id
var formId = "users-form";
var form = document.forms[formId];
var userId = form.querySelector("[name=user-id]");
var userName = form.querySelector("[name=user-name]");
var userAge = form.querySelector("[name=user-age]");
var userIdValue = userId.value;
// Example XHR with those values
fetch('/users/' + userIdValue, {
method: 'POST',
body: new FormData(form)
})
.then(loadingRequest)
.then(function () {
// Reset every form value
userId.value = '';
userName.value = '';
userAge.value = '';
})
.then(loadedRequest);
// Say we have a list of items in list items with an anchor
// We need to retrieve the name and link of each element
// Every "a" child of a "li" child of an "ul" with a "list-items" class
var list = document.querySelectorAll("ul.list-items li a");
// We can use "map" because querySelector() returns an array
var listData = list.map(function (anchor) {
return {
// We could use innerHTML if to retrieve the HTML
text: anchor.innerText,
link: anchor.getAttribute("href"),
};
});
console.log(listData);
// -> [{"text": "fisrt", "link": "/articles/first"}, {"text": "second", "link": "/articles/second"}];
// Above we used ".then(loadingRequest) ".then(loadedRequest)"
// A div with a "form-loading-request" id that is hidden by default
// We call the element before, to avoid a DOM query on every call
var loadingRequestElement = document.getElementById("form-loading-request");
var loadingRequest = function () {
loadingRequestElement.style.opacity = "0.8";
};
var loadedRequest = function () {
loadingRequestElement.style.opacity = 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment