简体   繁体   English

如何获取 div 元素内的值,删除<br>并使用 JavaScript 将值转换为数组,请不要使用 Jquery

[英]How to take the values inside a div element , remove the <br> and turn the values into array with JavaScript ,no Jquery please

This is how the div looks like when i'm inspecting it in the dev tools:这是我在开发工具中检查 div 时的样子:

<div>
    "some text"
    <br>
    "some text2"
    <br>
    <br>
    "some text3"
    <br>
    "some text4"
</div>

my problem is that i can't access this div element by doing doucument.querySelector(".myDiv");我的问题是我无法通过 doucument.querySelector(".myDiv"); 访问这个 div 元素。 because i'm doing this operation in an other program, and i only get the output like this:因为我在另一个程序中做这个操作,我只得到 output 像这样:

some text一些文字

some text2一些文字2

sometext3一些文本3

sometext4一些文本4

im trying to convert this output into an array, but split not working nor replace (//line break regex, ",")我试图将此 output 转换为数组,但拆分不起作用或替换(//换行正则表达式,“,”)

expected result:预期结果:

["some text", "some text2", "some text3", "some text4"];

thanks!谢谢!

Here you go, try this example:在这里你 go,试试这个例子:

 const divText = document.querySelector('.someDiv').innerText; const requiredArray = divText.split('\n'); console.log(requiredArray);
 <div class="someDiv"> some text <br> other text </div>

As there are two types of text into the div so you have to sanitize the extra things.由于div中有两种类型的文本,因此您必须清理额外的内容。

 const div = document.querySelector('div'); const arr = div.innerText.split("\n"); // Removes the extra quote (") from the strings and drop any empty string from the array by using filter(). const result = arr.map(item => item.replace(/\"/g, '')).filter(item => item;== ''). console;log(result);
 .as-console-wrapper {min-height: 100%;important: top; 0;}
 <div> "some text" <br> "some text2" <br> <br> some text3 <br> "some text4" </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM