How to display HTML class of current node in JS - javascript

I have variables which:
display the result (result), and
reference the current node (thisNode).
What do I need to change in my code so that it would display the HTML class?
var thisNode = document.body.firstChild;
var result = document.getElementById("resultOfButton");
result.InnerHTML = thisNode.;
/* Here, in JS are there any ways like displaying the class name,
like nodeClass */
Please give recommendations for my code. There may be some errors. Thank you.
var thisNode = document.body.firstChild;
var result = document.getElementById("resultOfButton");
var block = false;
function buttonDown()
{
if(block == true)
{
thisNode = thisNode.parentElement.firstChild;
block = false;
}
thisNode = thisNode.nextSibling;
result.innerHTML = thisNode.nodeName;
if(thisNode == thisNode.parentNode.lastChild)
{
block = true
}
}
function buttonUp()
{
// not done now...
}
function buttonEnter()
{
thisNode = thisNode.firstChild;
result.innerHTML = thisNode.c;
}
function buttonBack()
{
// not done now...
}

I think you're asking for the className attribute. I copied your first sample and added some code so you can run it on this page. You'll get the second emoji replaced by the class name of the inserted element.
var thisNode = document.getElementById("thisNode"); // document.body.firstChild;
var result = document.getElementById("resultOfButton");
result.innerHTML = thisNode.className; /*Here, in JS are there any ways like displaying the class name, like nodeClass*/
<div id="thisNode" class="sample-class">🙂</div>
<div id="resultOfButton">🙃</div>
Quoting MDN:
"The className property of the Element interface gets and sets the value of the class attribute of the specified element."

Related

I am learning how to convert javascript to jquery but can't get past the global variables to convert properly

Here is an excerpt of the original code in javascript. For the global variables, how would I convert those to jquery so I am able to resuse them later in the code, as I continue to convert it all over to jquery?
/* global variables tracking status of each form section */
var acresComplete = true;
var cropsComplete = true;
var monthsComplete = true;
var fuelComplete = true;
/* global variables referencing sidebar h2 and p elements */
var messageHeadElement = document.getElementById("messageHead");
var messageElement = document.getElementById("message");
/* global variables referencing fieldset elements */
var acresFieldset = document.getElementsByTagName("fieldset")[0];
var cropsFieldset = document.getElementsByTagName("fieldset")[1];
var monthsFieldset = document.getElementsByTagName("fieldset")[2];
var fuelFieldset = document.getElementsByTagName("fieldset")[3];
/* global variables referencing text input elements */
var monthsBox = document.getElementById("months");
var acresBox = document.getElementById("acres");
/* verify acres text box entry is a positive number */
function verifyAcres() {
var validity = true;
var messageText = "";
try {
if (!(acresBox.value > 0)) {
throw "Please enter a number of acres greater than 0.";
}
}
catch(message) {
validity = false;
messageText = message;
acresBox.value = ""; // remove erroneous entry from input box
}
finally {
acresComplete = validity;
messageElement.innerHTML = messageText;
messageHeadElement.innerHTML = ""; // remove any former recommendation heading
testFormCompleteness();
}
}
To select elements using ids, you can use $('#some-id'). In your code, it would be
const messageHeadElement = $('#messageHead');
const messageElement = $('#message');
As for the fieldsets, you can use the tag selector like so:
const fieldsets = $('fieldset');
//.eq(0) returns a jQuery object while [0] will return the DOM element.
const acresFieldset = fieldsets.eq(0);
Nevermind, I figured out how to do what I needed to do. I needed to just delete the global variables and then go to each reference of the now deleted global variable and replacec that with one line of jquery to reference the change I need to make. In the below snippet, I have deleted the variables for the sidebar elements and have made the jquery code work without a global variable.
/* global variables tracking status of each form section */
var acresComplete = true;
var cropsComplete = true;
var monthsComplete = true;
var fuelComplete = true;
/* global variables referencing fieldset elements */
var acresFieldset = document.getElementsByTagName("fieldset")[0];
var cropsFieldset = document.getElementsByTagName("fieldset")[1];
var monthsFieldset = document.getElementsByTagName("fieldset")[2];
var fuelFieldset = document.getElementsByTagName("fieldset")[3];
/* global variables referencing text input elements */
var monthsBox = document.getElementById("months");
var acresBox = document.getElementById("acres");
/* verify acres text box entry is a positive number */
function verifyAcres() {
var validity = true;
var messageText = "";
try {
if (!(acresBox.value > 0)) {
throw "Please enter a number of acres greater than 0.";
}
}
catch(message) {
validity = false;
messageText = message;
acresBox.value = ""; // remove erroneous entry from input box
}
finally {
acresComplete = validity;
$("#message").text(messageText);
$("#messageHead").text("");
testFormCompleteness();
}
}

Can't fetch image URL and use it as CSS background image

I have a Unordered List wist List Items that are created using the Fetch method. The data is JSON data and needs to be relayed to an HTML document
I want the created list items to have a CSS-background based on the JSON data URL. It looks something like this;
fetch(url).then(function(response){
return response.json();
JSON.stringify(data);
}).then(function(data){
for(var i=0;i<data.length;i++){
var createListItem = document.createElement("li");
createListItem.className = "listItem";
var listItem = document.querySelector(".listItem");
var createHeaderItem = document.createElement("h3");
createHeaderItem.innerHTML = data[i].title;
ul.appendChild(createListItem);
createListItem.appendChild(createHeaderItem);
if (data[i] && data[i].media[0] && data[i].media[0].url) {
listItem.style.backgroundImage = "url('"+""data[i].media[0].url""+"')";
} else {
listItem.style.backgroundImage = "none";
}
}
});
I can't get the list item style background to relay the URL. What is the correct way of grabbing the data.media.url and using it as CSS list-item property?
It looks like you have excessive quotes
Try removing the quote after the first + and before the second +
listItem.style.backgroundImage = "url('"+""data[i].media[0].url""+"')";
To
listItem.style.backgroundImage = "url('"+ data[i].media[0].url +"')";
Edited:
for(var i=0;i<data.length;i++){
var createListItem = document.createElement("li");
createListItem.className = "listItem";
var createHeaderItem = document.createElement("h3");
createHeaderItem.innerHTML = data[i].title;
ul.appendChild(createListItem);
createListItem.appendChild(createHeaderItem);
var listItem = document.querySelector(".listItem");
if (data[i] && data[i].media[0] && data[i].media[0].url) {
listItem.style.backgroundImage = "url('"+ data[i].media[0].url +"')";
} else {
listItem.style.backgroundImage = "none";
}
What has changed?
You never declared
var ul = document.createElement("ul");
I'm going to assume this is global variable and declared outside this scope otherwise you have additional problems that needs addressing.
I've moved the following code (see below) further down the code. You attempted to access a DOM element using document.querySelector() on an element that has not yet been added to the DOM. As a result of this you always got null returned.
var listItem = document.querySelector(".listItem");
This excessive quote I raised earlier still stands.
As I have mentioned in my comments listItem is null. This is due to the fact that createListItem has yet to be added to the DOM and .querySelector(..) checks the current DOM tree when the function is called.
There is no need for listItem to exist since you're manipulating and appending to createListItem. So rather than trying to assign .style.backgroundImage = ".." to listItem add it to createListItem:
if (data[i] && data[i].media[0] && data[i].media[0].url) {
createListItem.style.backgroundImage = "url('"+data[i].media[0].url+"')";
} else {
createListItem.style.backgroundImage = "none";
}
Additionally if .listItem, the CSS class, does not have a default background-image of some sort you can omit the above else clause as it is unnecessary:
if (data[i] && data[i].media[0] && data[i].media[0].url) {
createListItem.style.backgroundImage = "url('"+data[i].media[0].url+"')";
}

How to add/remove a value from stored html

According to the user navigation to pages, i would like to show appropriate side bars. so I am basically getting html of side bar and putting in empty.
and i am storing the sidebar to object. before i add to object i would like to add an id to side bar. i am trying but not working;
here is my try:
var ob = {};
var catcheBars = {};
var sidebar = $('div.sidebar');
var catchedBar = sidebar;
sidebar.empty();
for(i=1; i <= 5; i++) {
if(!ob.hasOwnProperty(i+'page')) {
ob[i+'page'] = catchedBar;
console.log($(ob[i+'page']).find('button').addClass('sidebar'+i)); //not able to add class
}
}
$("#sideBar").html(ob['1page']); //nothing append to live..
console.log(ob);
my try is not working. when i do the mistake, or what is the correct way?
thanks in advance
Update
Live Demo
I removed the empty() function. it works fine.
here is he updated result
var ob = {};
var catcheBars = {};
var sidebar = $('div.sidebar');
var catchedBar = sidebar;
for(i=1; i <= 5; i++) {
if(!ob.hasOwnProperty(i+'page')) {
ob[i+'page'] = catchedBar;
console.log($(ob[i+'page']).find('button').addClass('sidebar'+i)); //not able to add class
}
}
$("#sideBar").html(ob['1page']); //nothing append to live..
console.log(ob);

Code updates color but not the actual text?

This chunk of code that I have updates the color of the text but not the actual text...
var lastWordTyped;
var ele = document.querySelector("#my_text");
//code
//...
lastWordTyped = capitalizeFirstLetterOfKeyword(lastWordTyped);
lastWordTyped = lastWordTyped.fontcolor("blue");
ele.innerHTML = lastWordTyped;
function capitalizeFirstLetterOfKeyword(keyword) {
var word;
word = keyword.charAt(0).toUpperCase() + keyword.slice(1);
return word;
}
When I step through it, is recognizing what the new string should be but it doesnt update the actual text to the new string, but it does change its color. Can anybody provide me with the reason as to why it won't update it?
You haven't declared lastWordTyped, so the capitalizeFirstLetterOfKeyword() gets an 'undefined' as input.
Working demo here:
http://jsfiddle.net/yc4mvm1n/1/
var lastWordTyped = "NewWord";
var ele = document.querySelector("#my_text");
lastWordTyped = capitalizeFirstLetterOfKeyword(lastWordTyped);
lastWordTyped = lastWordTyped.fontcolor("blue");
ele.innerHTML = lastWordTyped;
function capitalizeFirstLetterOfKeyword(keyword) {
var word;
word = keyword.charAt(0).toUpperCase() + keyword.slice(1);
return word;
}
Your code looks fine to me.
http://plnkr.co/edit/mRllGWD2bNTxxyWrJENZ?p=preview
Try posting some more code.
function capitalizeFirstLetterOfKeyword(keyword) {
var word;
word = keyword.charAt(0).toUpperCase() + keyword.slice(1);
return word;
}
is returning proper capitalized word back, I am assuming that you are setting values to lastWordTyped somewhere in your //code section
Make sure the element #my_text exists before the JS code is run. You can do this by putting the script at the bottom of the body, or by using
window.onload = function() {
// your code here
}

Check if team already added

I have a page where you can invite teams. Clicking "Invite teams" makes a popup box appear showing a search input. The search-function is AJAX based. When a team is found through your search word(s), you'll have to click on the team whereupon the team will be showed in a "Invited-teams"-box.
It works in a way that when you "add" the team, a hidden input field is generated containing the team's ID as a value. The problem is that with my current code, it is possible to add the same team as many times as you wish. I should be possible to check, if the team can be found in the hidden-input-data. If it already exists, it should not be possible to add the sane team.
My current javascript-code can be found beneath here. Please notice that I have tried to make the code that checks the team, but it doesn't work.
function addTeam(tid) {
// Grab the input value
var teamName = document.getElementById(tid).innerHTML;
var teamID = document.getElementById(tid).id;
// If empty value
if(!teamName || !teamID) {
alert('An error occured.');
} else {
//Tried to do the "team-adlready-added"-test, but it doesn't work
var stored_teams = $t('#store-teams').getElementsByTagName('input');
for (var i = 0; i < stored_teams.length; i++) {
var stored_team = stored_teams[i];
if(stored_team.value == teamID) {
break;
var team_already_added = 1;
}
alert(team_already_added);
}
if((team_already_added) || team_already_added != 1) {
// Store the team's ID in hidden inputs
var store_team = document.createElement('input');
store_team.type = 'hidden';
store_team.value = teamID;
// Append it and attach the event (via onclick)
$t('#store-teams').appendChild(store_team);
// Create the teams with the value as innerHTML
var div = document.createElement('div');
div.className = 'team-to-invite';
div.innerHTML = teamName;
// Append it and attach the event (via onclick)
$t('#teams').appendChild(div);
}
div.onclick = removeTeam;
}
return false;
}
Thanks in advance.
I just want to give you a hint for a possible solution without html elements.
You can create a new functional object for team:
var Team = function (id, name) {
this.name = name;
this.id = id;
}
Create an array which will contain teams:
var TeamList = [];
Add you Teams:
TeamList.push(new Team(1, "Team 1"));
TeamList.push(new Team(2, "Team 2"));
TeamList.push(new Team(3, "Team 3"));
TeamList.push(new Team(4, "Team 4"));
Write a function which loops trough the list of teams and checks with the id if a team already exists:
function containsTeam(id) {
for (var i = 0; i < TeamList.length; i++) {
if (TeamList[i].id == id) {
return true;
}
}
return false;
}
Just check it:
containsTeam(1); //returns true
containsTeam(5); //returns false
Have a look at the jsFiddle DEMO and open the console to see the output.
EDIT: In addition, to remove an element you can write a function which looks pretty much the same as the containsTeam function. Just use array.splice instead of returning true:
function removeTeam(id) {
for (var i = 0; i < TeamList.length; i++) {
if (TeamList[i].id == id) {
TeamList.splice(i, 1);
}
}
}
And remove a team:
removeTeam(3);
Your variable scope is off.
You declare team already added in the wrong spot.
Declare it with team name and team id and it will get you in the right direction

Categories

Resources