简体   繁体   English

HTML和Javascript更改尖括号(<>)内的内容

[英]HTML & Javascript change content inside angle brackets ( < > )


Just wanted to know if it is possible to change with pure Javascript the content between the angle brackets in a HTML tag. 只是想知道是否有可能使用纯Javascript来更改HTML标记中尖括号之间的内容。
By this I mean all the content, not only the tag name, not only the id, not only the class and all the different attributes but everything inside, even non standart HTML code. 我的意思是所有内容,不仅是标签名称,不仅是ID,不仅是类和所有不同的属性,还包括内部的所有内容,甚至是非标准的HTML代码。

One small example: 一个小例子:
Before 之前

<div id="myID" class="myCLASS" whaterver-content ></div>

After Javascript DOM function Javascript DOM功能之后

<div id="myID" class="myCLASS" other-content ></div>

I know tag name, id and class can be modified with DOM Element Object functions in JS. 我知道可以使用JS中的DOM元素对象功能来修改标签名称,ID和类。 Is there any nice function that does the same for data not inside quotes and not before an attribute? 是否有任何不错的函数可以对不在引号内和属性前的数据进行相同的处理?

Thanks for your answers. 感谢您的回答。

EDIT: I just saw this Set attribute without value by asking the question on another way. 编辑:我只是通过另一种方式问这个问题,看到这个Set属性没有价值 But is the result the same? 但是结果是一样的吗? Or will there be ="" after the attribute? 还是在属性后会有=“”?

I do not like the accepted answer. 我不喜欢被接受的答案。 You should not be manipulating HTML as string. 您不应该将HTML作为字符串来处理。 It is not safe and performance is usually really bad. 它并不安全,性能通常确实很差。

Imagine that whaterver-content is actual text somewhere inside that div, for example as user input. 想象一下, whaterver-content是该div中某个地方的实际文本,例如作为用户输入。 It will get replaced when it should not be. 它将在不应该的时候被替换。

Please use DOM manipulation directly: 请直接使用DOM操作:

var element = document.getElementById('myID');
element.removeAttribute("whaterver-content");
element.setAttribute("other-content", "");

How about using replace on the element's outerHTML attribute? 如何在元素的outerHTML属性上使用replace

 function change() { document.getElementById('myID').outerHTML = document.getElementById('myID').outerHTML.replace('whaterver-content','other-content'); console.info(document.getElementById('myID').outerHTML); } 
 <div id="myID" class="myCLASS" whaterver-content ></div> <input type='button' onclick='change();' value='change' /> 

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

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