我如何以这种方式从div中获取文本?

时间:2019-02-25 16:08:30

标签: javascript html

我想使用javascript。 在br之前,我也有文本,该文本会发生变化。可以是4/20或10/20等。

var questionString = document.getElementsByClassName("question")[0].innerText;


console.log(questionString)
<DIV class="question">1/20
  <BR>THIS IS A QUESTION?</DIV>

4 个答案:

答案 0 :(得分:1)

这是你的问题。

var questionString = document.getElementsByClassName("question")[0].innerHTML.split('<br>')[1];
console.log(questionString)
<DIV  class="question">1/20<BR>THIS IS A QUESTION?</DIV>

答案 1 :(得分:0)

如果您想在无线电通信局之后提出问题,请尝试以下操作:

let qs = [];
document.querySelectorAll(".question").forEach((d) =>
  qs.push(d.innerText.replace(/\d{1,}\/\d{1,}\s+/, ""))
)
console.log(qs)
<DIV class="question">1/20
  <BR>THIS IS QUESTION 1 of 20</DIV>
<DIV class="question">2/20
  <BR>THIS IS QUESTION 2 of 20</DIV>

答案 2 :(得分:0)

到4/20,您的意思是当前问题是总共20个问题中的第四个问题,对吗? 我相信您的要求是,当用户单击下一步按钮时,您希望将文本“ 4/20”更改为“ 5/20”。

// have a reference to the question text's DOM
var question_no_dom = document.getElementById("question_no");
var question_dom = document.getElementById("question");
// list of questions
var questions = ["1. How tall is mount everest?",
                "2. What is the capital city of Russia?", 
                "3. How far way is the sun from the earth?"];
// start with the first question
var current_quest_no = 0;
var total_no_quest = 3

question_no_dom.innerText = (current_quest_no+1)+'/'+total_no_quest;
question_dom.innerText = questions[current_quest_no];

function onNext() {
  if(current_quest_no < total_no_quest-1) {
    current_quest_no++;
    question_no_dom.innerText =   (current_quest_no+1)+'/'+total_no_quest;
  question_dom.innerText = questions[current_quest_no];
  }
}
<div id="question_no"></div><br>
<div id="question"></div><br>
<button onclick="onNext()">Next&nbsp;></button>

答案 3 :(得分:-1)

抓取div的第一个子节点(给定html始终是您想要的文本节点),然后对其进行修剪以删除多余的空格和换行符。

var questionString = document.getElementsByClassName("question")[0].childNodes[0].textContent.trim()


console.log(questionString)
<DIV class="question">1/20
  <BR>THIS IS A QUESTION?</DIV>