插入仅在元素之后打开HTML标记? [英] Insert just opening HTML tags after an element?

查看:97
本文介绍了插入仅在元素之后打开HTML标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在页面上的H1元素之后插入几个打开的DIV标签,而不插入相应的结束标签(因为结束标签包含在我无法访问的包含的脚注文件中)。


现有代码:

 < body> 
< h1> Heading One< / h1>
...页面内容...
< / div>
< / div>
< / body>

新代码:

 <身体GT; 
< h1> Heading One< / h1>
< div id =foo>
< div id =baa>
...页面内容...
< / div>
< / div>
< / body>

DOM方法将div插入为完整(闭合)元素,'createTextNode'插入转义字符和' innerHTML'需要一个元素来插入。甚至试图插入一个脚本元素与document.write没有任何运气。



任何想法(jQuery都可以)?

更新
以下工作:

  document.body.innerHTML = document.body.innerHTML.replace('< / h1>' ,'< / h1>< div id =foo>< div id =baa>')

$ b $正如 Asad 指出的那样,解决方案(现在看起来很明显)是在HTML上使用字符串方法而不是DOM方法。

$ b $如果你正在处理DOM操作,使用DOM操作方法。如果您正在处理HTML操作,请使用字符串操作方法。

  h1.parentElement.innerHTML = h1.parentElement.innerHTML。替换(< h1> Heading One< / h1>,< h1> Heading One< / h1>< div>< div> 


I would like to insert a couple of opening DIV tags after the H1 element on a page, without inserting the corresponding closing tags (since the closing tags are contained in an included footer file which I don't have access to).

i.e. Existing code:

<body>
<h1>Heading One</h1>
... page content...
</div>
</div>
</body>

New code:

<body>    
<h1>Heading One</h1>
<div id="foo">  
<div id="baa">  
... page content...
</div>
</div>
</body>

DOM methods insert the div as a complete (closed) element, 'createTextNode' inserts escaped characters and 'innerHTML' needs an element to insert into. Have even tried to insert a script element with document.write without any luck.

Any ideas (jQuery would be fine)?

Update The following worked:

document.body.innerHTML = document.body.innerHTML.replace('</h1>','</h1><div id="foo"><div id="baa">')

As pointed out by Asad the solution (which now seems obvious of course) is to use string methods on the HTML rather than DOM methods.

解决方案

If you're dealing with DOM manipulation, use DOM manipulation methods. If you're dealing with HTML manipulation, use string manipulation methods.

h1.parentElement.innerHTML = h1.parentElement.innerHTML.replace("<h1>Heading One</h1>","<h1>Heading One</h1><div><div>");

这篇关于插入仅在元素之后打开HTML标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆