我試圖得到一個元素中的文本,刪除一些字符串的額外空間,增加一個問號&那麼更新後的字符串放入另一個元素使用Javascript - 從的textContent
然而,當元素被返回,標記會在&也會將問號放在元素中的全新行上之前生成額外的不需要的空間。
這就是從一個控制檯日誌返回
// Set Variables for Dynamic Copy Function
let \t choiceNode = document.querySelectorAll('.choice');
let \t dynamicCopyNode = document.querySelector('.dynamic-copy');
// Update the text type on dynamic copy & append a question mark + remove 'The '
function updateChoice() {
\t let choiceSelected = this.textContent + '?';
\t let choiceSelectedTrim = choiceSelected.replace('The ', '');
\t dynamicCopyNode.textContent = choiceSelectedTrim;
}
// Click listener to trigger the function
Array.from(choiceNode).forEach(function(element) {
element.addEventListener('click', updateChoice);
});
<form>
\t <div class="choice-wrapper">
\t \t <div class="choice">
\t \t \t <input type="radio" name="choice" id="one" value="1">
\t \t \t <label for="one">
\t \t \t \t <p class="name">The first choice</p>
\t \t \t </label>
\t \t </div>
\t \t <div class="choice">
\t \t \t <input type="radio" name="choice" id="one" value="2">
\t \t \t <label for="one">
\t \t \t \t <p class="name">The second choice</p>
\t \t \t </label>
\t \t </div>
\t \t <div class="choice">
\t \t \t <input type="radio" name="choice" id="one" value="3">
\t \t \t <label for="one">
\t \t \t \t <p class="name">The third choice</p>
\t \t \t </label>
\t \t </div>
\t \t <div class="choice">
\t \t \t <input type="radio" name="choice" id="one" value="4">
\t \t \t <label for="one">
\t \t \t \t <p class="name">The fourth choice</p>
\t \t \t </label>
\t \t </div>
\t \t <div class="error-wrap">
\t \t \t <label class="error" for="choice" generated="true"></label>
\t \t </div>
\t </div>
\t <div class="copy-wrapper">
\t \t <div class="variable-copy">
\t \t \t <p>Why did you choose</p>
\t \t \t <h1 class="dynamic-copy"></h1>
\t \t </div>
\t </div>
</form>
我試圖做到的,是像這樣首選回報?
您需要'p'標籤,而不是整個div的文本內容。 –
哦,該死 - 我現在明白了。但是,當我嘗試從點擊的「choice」中獲得最接近的'.name'時,它會返回null? – Minum