0


Just wanted to know if it is possible to change with pure Javascript the content between the angle brackets in a HTML tag.
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.

One small example:
Before

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

After Javascript DOM function

<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. 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. But is the result the same? Or will there be ="" after the attribute?

Ascor8522
  • 139
  • 1
  • 3
  • 11

2 Answers2

2

I do not like the accepted answer. You should not be manipulating HTML as string. 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. It will get replaced when it should not be.

Please use DOM manipulation directly:

var element = document.getElementById('myID');
element.removeAttribute("whaterver-content");
element.setAttribute("other-content", "");
Rok Kralj
  • 46,826
  • 10
  • 71
  • 80
  • I also found this solution (look at the edit)... both are working but I agree with you it's maybe best to work with DOM. Btw, as the value of the attribute is blank, will there be ="" after the attribute? – Ascor8522 Aug 28 '17 at 14:31
  • Short answer: it will work as you expect. Long answer: missing attribute value and empty string attribute are one and the same thing in HTML5. – Rok Kralj Aug 28 '17 at 14:48
1

How about using replace on the element's outerHTML attribute?

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' />
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
  • @Ascor8522 What exactly do you want then? Can you specify better? – Koby Douek Aug 27 '17 at 11:40
  • In my case, i'd like to change the whole tag, not just getting his "value" or a string of it – Ascor8522 Aug 27 '17 at 11:40
  • What I wrote changes the whole tag, without changing its value... Isn't that it? Can you give a better example? – Koby Douek Aug 27 '17 at 11:42
  • Oh, sorry, didn't see that the result was different ^^ I tougth it was just an outerHTML function... By the way, it's exactly what I was expecting ;) Thanks a lot – Ascor8522 Aug 27 '17 at 11:44