doukuang6795 2013-04-10 11:23
浏览 243
已采纳

如何将p标签插入现有的div / HTML中

I scraped html data from web sites using simplehtmldom_1_5 and after scraped I want to insert every text in a <p> tag with different id of every <p> tag as a explained below:

 Suppose scrapped data:

          <div class="maincontainer">
            <div class="first">
            first text 
            </div>
            <div class="second">
            second text 
            </div>

            <div class="third">
            third text 
            </div>

            <div class="fourth">
            fourth text 
            </div>
fifth string 
          </div>

    And I want result like this below:

          <div class="maincontainer">
            <div class="first">
            <p  id="1">first text </p> 
            </div>
            <div class="second">
            <p  id="2">second text </p>
            </div>

            <div class="third">
            <p  id="3">third text </p>
            </div>

            <div class="fourth">
            <p  id="4">fourth text </p>
            </div>
    <p  id="5">   fifth string </p>
          </div>

Guys I want to do this during scraping not after scraping.

  • 写回答

3条回答 默认 最新

  • duanjia1870 2013-04-10 11:37
    关注

    You can use jQuery like this:

    $(document).ready(function () {
        $('div').each(function (i) {
            var $this = $(this);
            if (!$this.find('div, span, div, img, ul, a').length) {
                var elData = $this.html();
                if ($.trim(elData) != '') {
                    var appendData = '<p  id="' + (i + 1) + '">' + elData + '</p>';
                    $this.html(appendData);
                }
            }
        });
    
    });
    

    @ JsFiddle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题