提问者:小点点

如何在这个JS结构中只向第一个DIV添加新类


我有一个文本框,当我从这个文本框中添加一些行,然后这些行添加到类似这样的结构中。

您可以通过复制/粘贴并插入到此文本框来检查这些行:

问题1:天空的颜色是……?

问题2:纸来自……?

问题3:一天几个小时?

问题4:长颈鹿是鱼?

但现在我的需要是只在第一行添加一个额外的类answer,如下所示:

我的所有JS文本框代码是:

null

const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;

sendButton.addEventListener('click', function() {
  // split the textarea entries into an array
  let lines = (textArea.value).split("\n");

  // iterate over each line, creating a div/span and inserting into the DOM
  lines.forEach( (line) => {
    let encodedLine = encodeHtmlEntity(line);
    let newElement = `<div class="quiz">${encodedLine}</div>`;
    
    innerDiv.innerHTML += newElement;
  });
  
  // reset the textarea
  textArea.value = '';

});

function encodeHtmlEntity(input) {
  var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
    return '&#' + i.charCodeAt(0) + ';';
  });

  return output;
}
<div id="inner"> </div>


<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">add text</button>

null

我怎么能那么做。请解决我的问题。我需要写哪些额外的代码行?

提前谢谢,爱你。


共3个答案

匿名用户

如果您确信总是存在至少一个“测验”类元素:

document.getElementsByClassName('quiz')[0].classList.add('answer')

[0]表示具有“quiz”类的第一个元素。

注意:如果根本没有“Quiz”类元素,那么:

document.getElementsByClassName('quiz')[0] === undefined

null

Cannot read property 'classList' of undefined

匿名用户

你可以这样做:

  // iterate over each line, creating a div/span and inserting into the DOM
  lines.forEach( (line, index) => {
    let encodedLine = encodeHtmlEntity(line);

    let classList = 'quiz';
    if (index === 0) {
      classList += ' answer'
    }

    let newElement = `<div class="${classList}">${encodedLine}</div>`;
    
    innerDiv.innerHTML += newElement;
  });

匿名用户

尝试添加一个索引,然后使用tha以符合条件的方式首先添加类

sendButton.addEventListener('click', function() {
  // split the textarea entries into an array
  let lines = (textArea.value).split("\n");

  // iterate over each line, creating a div/span and inserting into the DOM
  lines.forEach( (line,i) => {
    let encodedLine = encodeHtmlEntity(line);
    let newElement = i===0 ? 
    `<div class="quiz answer">${encodedLine}</div>` :
    `<div class="quiz">${encodedLine}</div>`
    
    innerDiv.innerHTML += newElement;
  });
  
  // reset the textarea
  textArea.value = '';

});