Javascript DOM のまとめ - JSchallenger

スポンサーリンク

はじめに

JSchallenger の Javascript Fundamentals – Javascript Sets のまとめです。
まとめページのトップは、JSchallenger まとめ です。

問題一覧と回答

正解のチェックが甘い気がします。
逆に、なぜ不正解なのか分からないものもあったり。

DOM selector methods

Select the button element on the page

In this scenario, the existing code adds an eventListener for a click event on a variable ‘buttonElem’. It expects ‘buttonElem’ to be the button element in the example UI. But, that element is not selected yet. Assign the button element to the variable ‘buttonElem’ with one of the existing selector methods. Click the button to verify that the code is working. Hint: Make use of the unique id identifier of the button element.

const buttonElem = document.getElementById("button");
  
buttonElem.addEventListener('click', () => {
  const oldText = buttonElem.innerText;
  return button.innerText = oldText === "ON" ? "OFF" : "ON";
});

Query descendent HTML elements

Here, the existing code expects the variables ‘buttonElem’ and ‘inputElem’ to represent the button and input elements in the example UI. Assign the respective elements to the variables. In this case, the two elements do not have unique identifiers – like for example an id. Instead they are direct descendents of a div element with id ‘wrapper’. Use an appropriate selector method! Click the button to verify that the code is working.

const buttonElem = document.querySelector("#wrapper button");
const inputElem = document.querySelector("#wrapper input");

buttonElem.addEventListener('click', () => {
  const oldText = inputElem.value;
  return inputElem.value = oldText === "ON" ? "OFF" : "ON";
});

Select multiple HTML elements

In this scenario, we are looking for a list of elements gathered in one variable – rather than only one element. Assign the list items in the view to the variable ‘listItems’ by using an appropriate selector method. Once you have completed the code below, verify it by hovering over the list items until all items have the value ‘ON’

// assign the correct elements to the variable
const listItems = document.querySelectorAll("#list li");

consthandleHover = (event) => {
  return event.target.innerText = 'ON';
};
if(listItems.length < 1) {
  listItems.forEach(item => item.addEventListener('mouseover', handleHover));
}

Query and exclude HTML elements

In this scenario, you need to query all list items that belong to the list with id ‘list’. But, exclude the ones with id ‘disabled’ Assign those items to the variable ‘listItems’ by using an appropriate selector method. Once you have completed the code below, verify it by clicking the button. The respective items should change their text.

// assign the correct elements to the variable
const listItems = document.querySelectorAll("#list li:not(#disabled)");

const button = document.getElementById('button');

consthandleClick = () => {
  listItems.forEach(item => {
  const oldText = item.innerText;
    return item.innerText = oldText === 'ON' ? 'OFF' : 'ON';
  })
};
if(listItems.length > 1) {
  button.addEventListener('click', handleClick);
}

Events and user interactions

Execute function on button click

The Javascript function handleText fills the input field with the words Hello World. But, there is no code to execute this function. Complete the existing code below such that the function is called when the button is clicked. Verify by clicking the button.

const button = document.getElementById('button');
const input = document.getElementById('input');

consthandleClick = () => {
  input.value = 'Hello World';
};

// type in your code here
button.addEventListener('click', handleClick);

Execute function when cursor moves onto element

The Javascript function changeText changes the text inside the circle. But again, there is no code to execute this function. Complete the existing code below such that the function is called when the cursor moves onto the circle. Verify that your code works by hovering over the circle.

const element = document.getElementById('element');

constchangeText = () => {
  element.innerText = 'Thanks!';
};

// type in your code here
element.addEventListener("mouseover", changeText);

Cursor enters and leaves element

In this scenario we want the color of the circle to change depending on the type of cursor movement. Use the function toggleColor to turn the circle orange when the cursor moves onto it. Reuse the same function to turn it black when the cursor leaves it. The tricky part is that you have to call toggleColor with different values for the parameter isEntering. Verify that your code is working by hovering the circle with the mouse cursor and leaving it again.

const element = document.querySelector('#element');
  
consttoggleColor = (isEntering) => {
   element.style.background = isEntering ? 'orange' : 'black';
};

element.addEventListener('mouseover', () => toggleColor(true));
element.addEventListener('mouseleave', () => toggleColor(false));

Move element with mouse cursor

This challenge might look more complicated than it actually is. The function moveRight below moves the rectangular element exactly 1 pixel to the right – unless it reaches the green bar. What you have to do is to call the function for each movement of your mouse inside the div element with id wrapper. Confirm that your code works by moving the cursor inside the wrapper div until you reach the green bar.

const element = document.querySelector('#element');
const wrapper = document.querySelector('#wrapper');

constmoveRight = () => {
    const wrapperWidth = wrapper.getBoundingClientRect().width;
    const elementWidth = element.getBoundingClientRect().width;
    const currentPosition = parseInt(element.style.left || 0, 10);
    if (currentPosition <= wrapperWidth - elementWidth) {
      element.style.left = `${currentPosition + 1}px`;
    }
};
  
 wrapper.addEventListener('mousemove', moveRight);

Drop element into another element

Here we want to drop the red square into the blue square. But, when you try to drop it there, it jumps back to where it was before. Make use of the function handleDrop to join the two elements together. You pass the challenge if you drop the red square into the blue one and it stays there.

const dragItem = document.querySelector('#dragItem');
const dropArea = document.querySelector('#dropArea');

consthandleDragOver = (event) => event.preventDefault();
dropArea.addEventListener('dragover', handleDragOver);

consthandleDrop = () => {
  dropArea.append(dragItem);
};

dropArea.addEventListener("drop",handleDrop);

DOM manipulation with JavaScript

Remove element from the DOM

You may not see it in the example UI, but underneath the red circle is a green circle. Extend the function removeRedCircle to remove the circle with id red from the DOM. Make sure that you really remove the element instead of just hiding it. Confirm that your code works by clicking the button.

直接取得したエレメントを remove() するだけじゃダメなのか?

const button = document.querySelector('#button');

constremoveRedCircle = () => {
  document.getElementById('red').remove();
};

button.addEventListener('click', removeRedCircle);
const button = document.querySelector('#button');

const removeRedCircle = () => {
  const redCircle = document.querySelector('#red');
  redCircle.parentNode.removeChild(redCircle);
};

Change id of HTML element

In this scenario the existing code listens to a click on the button. When the button is clicked, the function changeInput is triggered. changeInput tries to select an input field with id inputEl. But, the existing input field does not have this id. Add some Javascript code to add the id inputEl to the existing input field. Verify that your code works by clicking the button.

const button = document.querySelector('#wrapper button');

constchangeInput = () => {
  const input = document.querySelector('#inputEl');
  if(input) {
    input.value = 'Hello World';
  }
};

button.addEventListener('click', changeInput);

document.querySelector('#wrapper input').setAttribute('id', 'inputEl');

Wrap element in div

The JavaScript code below installs en eventListener on a variable btn. A button element that is a descendent of another element with id wrapper was assigned to the variable btn. But, the existing button element has no parent node with id wrapper. Make the code work by creating a new element with id wrapper that wraps the existing button element. Verify your solution by clicking the button. It should change its text. Hint: you might have to use the following methods: querySelector, createElement, setAttribute, append.

手元ではこれで動いたのだがなぜか正解にならず。

// type in your code here
const wrapper = document.createElement("div");
wrapper.setAttribute('id', 'wrapper');
document.body.insertBefore(wrapper, button);
wrapper.append(document.getElementById('button'));

// expects button to be child of element with id 'wrapper'
const btn = document.querySelector('#wrapper button');

if(btn) {
  consthandleClick = () => {
    btn.innerText = 'Thank you! ❤️'
  }
  btn.addEventListener('click', handleClick)
}

これだと正解。

// type in your code here
const wrapper = document.createElement("div");
wrapper.setAttribute('id', 'wrapper');
const button = document.getElementById('button');
button.before(wrapper);
wrapper.append(button);

// expects button to be child of element with id 'wrapper'
const btn = document.querySelector('#wrapper button');

if(btn) {
  consthandleClick = () => {
    btn.innerText = 'Thank you! ❤️'
  }
  btn.addEventListener('click', handleClick)
}

authors’ solution はこれ。

const button = document.querySelector('#button');
  
const wrapper = document.createElement('div');
wrapper.setAttribute('id', 'wrapper');
button.parentNode.append(wrapper);
wrapper.append(button);

const btn = document.querySelector('#wrapper btn');

if(btn) {
  consthandleClick = () => {
    btn.innerText = 'Thank you! ❤️'
  }

  btn.addEventListener('click', handleClick)
}

Create new list item and add to DOM

Extend the JavaScript code below to interact with the displayed HTML elements. Enter a new todo in the input field. Once you click the button, the new todo item should appear at the bottom of the list. Confirm your code by creating a new todo!

const button = document.getElementById('button');
button.addEventListener('click' , () => {
  // type in your code here
  const li = document.createElement("li");
  li.textContent = document.getElementById('input').value;
  document.getElementById('list').append(li);
});
const button = document.getElementById('button');
button.addEventListener('click' , () => {
  const input = document.getElementById('input');
  const list = document.getElementById('list');
  const newItem = document.createElement('li');
  newItem.innerText = input.value;
  list.append(newItem);
});

DOM fundamentals

Check the checkbox

Your first JavaScript DOM exercise. Let’s start simple. Extend the JavaScript code below to interact with the displayed HTML elements. Once you click the button, the checkbox should be checked. Confirm your code by clicking the button!

const button = document.getElementById('button');
button.addEventListener('click', () => {
  // type in your code here
  document.getElementById('checkbox').checked = true;
});
const button = document.getElementById('button');
button.addEventListener('click', () => {
  const checkbox = document.getElementById('checkbox');
  checkbox.checked = true;
});

Get full-name from inputs

Extend the JavaScript code below to interact with the displayed HTML elements. This time we are looking for the full name. When the button is clicked, combine the names of the first two input fields. Insert the full name in the third input field. Hint: Check if your code still works if you change the first or last name. Confirm your code by clicking the button!

const button = document.getElementById('button');
button.addEventListener('click' , () => {
  const firstName = document.getElementById('firstName');
  const lastName = document.getElementById('lastName');
  const fullName = document.getElementById('fullName');
  fullName.value = firstName.value + ' ' + lastName.value;
});

Increment the counter on button click

Extend the JavaScript code below to interact with the displayed HTML elements. On each button click, increase the value of the button by 1. Confirm your code by clicking the button!

最初これで正解になってしまったけども、これは文字列のまま足しているので明らかにダメだろう。

const button = document.getElementById('button');
button.addEventListener('click' , () => {
  // type in your code here
  button.textContent = button.textContent + 1;
});

正解はこれ。

const button = document.getElementById('button');
button.addEventListener('click' , () => {
  const oldValue = parseInt(button.innerText, 10);
  button.innerText = oldValue + 1;
});

Input filter list

In this challenge, we create a dynamic input filter with JavaScript. Extend the code below to interact with the displayed HTML elements. Type a search term in the input field. The displayed items in the list should match your search term. The rest of the list elements should be hidden.

この問題は思いつかなかったので無理矢理やってしまった。。

const input = document.getElementById('input');
input.addEventListener('input', () => {
  // type in your code here
  document.querySelectorAll('#list li').forEach((e) => {
    if (e.textContent.indexOf(input.value) !== -1) {
      e.style.display = '';
    } else {
      e.style.display = 'none';
    }
  });
});
const input = document.getElementById('input');
input.addEventListener('input', () => {
  const listItems = document.querySelectorAll('#list li');
  listItems.forEach(li => {
    if(li.innerText.includes(input.value)) return li.hidden = false;
    return li.hidden = true;
  })
});

Pop the balloons

Make the balloons pop by hovering over them. Extend the JavaScript code below to interact with the displayed HTML elements. Every time you hover over a balloon, it should become invisible. Your goal is to pop all the balloons one after the other.

list で event listner 設定すれば mouseover なら子要素にも適用されたか。。

const list = document.getElementById('list');
list.childNodes.forEach( e => {
   e.addEventListener('mouseenter', () => {
      e.style. visibility = 'hidden';
   });
});
const list = document.getElementById('list');
consthandleHover = event => {
  if(event.target !== list) {
    event.target.style.visibility = 'hidden';
  }
};

list.addEventListener('mouseover', handleHover);

Recursive functions

Stop and restart the moving button

This is a good exercise to learn about recursive functions. The function move in the code below moves the button 1px to the left or the right. It is recursive because it calls itself again and again. This keeps the button moving. Extend the JavaScript code. Once you click the button, it should stop moving. When you click it again, it should move again. Confirm your code by clicking the button twice.

const button = document.getElementById('button');
let stopped = false;
 
functionmove(isReturning) {
 const width = button.parentNode.clientWidth;
 const left = parseInt(button.style.left , 10) || 0;
 if (!stopped) {
    button.style.left = (isReturning ? left - 1 : left + 1) + 'px';
    setTimeout(() => move ((isReturning && left > 0) || left === width - button.clientWidth), 10);
 };
};
 
move();
 
button.addEventListener('click', () => {
  stopped = !stopped;
  move();
});

コメント

タイトルとURLをコピーしました