[英]How i can store all content from <p> tag in array using javascript and jquery?
Following is the code i am working on以下是我正在处理的代码
var all=$('p').text(); var len_all=$('p').length; var all_array=[]; for (var i=0; i < len_all; i++) { console.log(all); all_array.push(all); } console.log(all_array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <p>I am out</p> <p>I am in</p>
I want all the <p>
tag contents in var all_array=[];
我想要var all_array=[];
中的所有<p>
标记内容I am getting following output in console:我在控制台中关注 output:
(2) ['I am outI am in', 'I am outI am in'] (2) ['我出我入','我出我入']
Expected is:预期是:
['I am out','I am in'] ['我出去了','我进来了']
That's because the $('p').text();
那是因为$('p').text();
will get the text
of all p
elements.将获得所有p
元素的text
。
You can achieve your goal with one line of vanilla javascript
, to get all p
elements by querySelectorAll
and map
to get each element textContent
您可以使用一行vanilla javascript
来实现您的目标,通过querySelectorAll
和map
获取所有p
元素来获取每个元素textContent
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <p>I am out</p> <p>I am in</p> <script> let all_array = [...document.querySelectorAll('p')].map(el => el.textContent); console.log(all_array) </script> </body> </html>
You're getting all of the values as one big value here:您在这里将所有值都视为一个大值:
var all=$('p').text();
And then repeatedly pushing that same value into an array:然后反复将相同的值推送到数组中:
all_array.push(all);
Instead, loop over the <p>
elements and push each value to the array:相反,循环遍历<p>
元素并将每个值推送到数组中:
var pElements = $('p'); var result = []; pElements.each(function (i, el) { result.push($(el).text()); }); console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <p>I am out</p> <p>I am in</p>
Try this:尝试这个:
var all=$('p');
var len_all=$('p').length;
var all_array=[];
for (var i=0; i < len_all; i++) {
console.log(all[i].text());
all_array.push(all[i].text());
}
console.log(all_array)
Or或者
var all=$('p');
var len_all=$('p').length;
var all_array=[];
for (var i=0; i < len_all; i++) {
console.log($(all[i]).text());
all_array.push($(all[i]).text());
}
console.log(all_array)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.