简体   繁体   中英

Adding html tags inside JavaScript

I am trying to add <button id="mybtn"></button> around the some text link but I am not sure how to make it. I tried a bit with document.write but I think I am using it wrong. When I click this button some text it replaces 'ZZZ' with nothing. However the changed link something here has a plain formatting. What I want it to do is add the <button id="mybtn"> and </button> around it, so the changed button stays with the same look.

Input:

document.getElementById("DiacriticsButton").innerHTML = "some text";

Output should be something like:

document.getElementById("DiacriticsButton").innerHTML = <button id="mybtn">"some text"</button>;

The current full script:

<script>
bodyText=document.getElementById("bodytext").innerHTML;
clearText = bodyText.replace(/ZZZ/g, "");
FStr = clearText.search("some text");

do {
  clearText = clearText.replace("something here","some text");  
  FStr = clearText.search("something here");
}
while(FStr!=-1);

function switchDiacritics() {
  if (document.getElementById("bodytext").innerHTML == clearText) {
    document.getElementById("bodytext").innerHTML = bodyText;
    document.getElementById("DiacriticsButton").innerHTML = "something here";
  } else {
    document.getElementById("bodytext").innerHTML = clearText;
    document.getElementById("DiacriticsButton").innerHTML = "some text";
  }
}

</script>

Are you doing anything to trigger this innerHTML change? Ex:

Wrapping the selection in window.onLoad{...}

OR

Wrapping it in a function to be triggered by an event listener. While if your goal is to simply place text within the tag in a static demeanour use the HTML attribute for a button with value="some text"

Do you look for something like this

document.getElementById("DiacriticsButton").innerHTML = '<button id="mybtn">"some text"</button>';

It is also possible to add element like this

var btn = document.createElement("button");
btn.innerHTML = "some text";
document.getElementById("DiacriticsButton").appendChild(btn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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