如何使用javascript在特定分区的范围内包装标题

时间:2014-04-25 07:25:15

标签: javascript joomla

这是我的实际代码:

<div class="content">
<h3>This is test text</h3>
</div>

我想这样:

<div class="content">
<div class="headers"><h3>This is test text</h3></div>
</div>

N.B。我使用的是Joomla!

1 个答案:

答案 0 :(得分:0)

这个功能可以解决问题:

function insert_headers(my_class)
{
   //get your content element
   var contents = document.getElementsByClassName(my_class);
   //loop on the elements found
   for(var i=0;i<contents.length;i++)
   {
      var content = contents[i];
      //get the html content
      var html_content = content.innerHTML;
      //replace the h3 tags to insert the span ones
      html_content = html_content.replace('<h3>', '<div class="headers"><h3>');
      html_content = html_content.replace('</h3>', '</h3></div>');
      //set the html content back
      content.innerHTML = html_content;
   }
}

所以如果你有这个:

<div class="content>
   <h3>This is test text</h3>
</div>

你这样做:

insert_headers('content');

你会得到这个:

<div class="content>
   <div class="headers"><h3>This is test text</h3></div>
</div>