简体   繁体   English

如何在文本框中的htmltext中获取所有标签

[英]how to get all tags inside htmltext in a textbox

I have webpage html source inside a textarea having id="textArea1" . 我在具有id="textArea1"textarea中有网页html源。

This Html code is containing some "p" tags. 该HTML代码包含一些"p"标签。 I want to get list of all p tags which lie in textArea of above code 我想获取位于上述代码的textArea中的所有p标签的列表

I want to get list of all p tags 我想获取所有p标签的列表

The text inside a <textarea> is a string, not sure what exactly you mean by list if you want substrings inside <p> you can use split() function... <textarea>中的<textarea>是一个字符串,如果要在<p>中使用子字符串,可以不确定使用list究竟是什么意思,可以使用split()函数...

$('#textArea1').change(function(){ // or any other event you want
 var text= $(this).val();
 var count= text.split('<p>').length-1;
 console.log(count);
});

check this JSFiddle 检查这个JSFiddle

Update: 更新:

as per comment, you can get the text inside occurances of <p></p> (assuming the html string inside textarea is in a valid format) as follows: 根据评论,您可以获取出现在<p></p>内的textarea (假设textarea内的html字符串为有效格式),如下所示:

$('#textArea1').change(function(){
 var text= $(this).val();
 var strings= text.split('<p>');
 for(i=1;i<strings.length;i++){
    strings[i]= strings[i].split('</p>')[0];
    console.log(strings[i]);
 }
});

JSFiddle 的jsfiddle

You cannot count the paragraph elements or the value inside the textarea as you could find them inside a seperate element. 您无法计算段落元素或textarea的值,因为您可以在单独的元素中找到它们。 Textarea is not meant for such purpose. Textarea并非用于此目的。

You can try counting all the p tags inside some other element like a seperate div which gets populated by the textarea value. 您可以尝试计算其他元素(例如单独的div)中所有的p标签,该元素由textarea值填充。

$('#textArea1').keyup(function () {
   $('div').html($(this).val());
   var totalPs = 0;
   $('div').find('p').each(function () {
     totalPs++;
   });
});

This would try counting the p elements. 这将尝试计算p元素。

It would: 它会:

  1. Handle an event on the textarea with the id textArea . 使用id textArea处理在textarea上的事件。

  2. Append the value of the textarea to the element (div here). 将textarea的值附加到元素(此处为div)。

  3. Create a variable with value 0. 创建一个值为0的变量。

  4. Find p elements inside the element and then iterate it n times; 在元素中找到p元素,然后迭代n次; n would be the number of paragraph elements. n将是段落元素的数量。

  5. Increment the value. 增加值。

You can use the value as the result and then get that inside the document or in the console. 您可以使用该值作为结果,然后在文档中或控制台中获取该值。

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

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