简体   繁体   中英

Is it possible to insert tags using insertAdjacentHTML() in order to wrap a certain element?

I am trying to add a label and span tag to radio button so as to style it. I want the input and span tags to be wrapped inside the label tag.

Note: I am making design changes to an existing template. The application uses XSLT to flush out the build in the installed template. I have tried to add a label and span tag in the XSLT structure, but resulted in crashing the final build. Only thing that let me add these tags was to insert them during run time.

function radio_button() {
var iframe = document.getElementById('questionFrame');
var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;

var inputs = innerDoc.getElementsByTagName("input");

for(var i = 0; i < inputs.length; i++) { 
if (inputs[i].type=='radio' ) { 
var radio=inputs[i];
radio.insertAdjacentHTML('beforebegin', '<label>');
radio.insertAdjacentHTML('afterend', '<span></span></label>');
   }
  } 
}

My expected result is to make it like this,

<label><input type="Radio" name="answer" value="x9" /><span><span></label>

but i am getting this instead,

<label></label><input type="Radio" name="answer" value="x9" /><span><span>

Is there any way to wrap the input tag inside the label tag? Thanks a lot. Appreciate any suggestions.

You can try cloneNode() to create the desired snippet and then use replaceChild with newly created elemnt(s)

 document.querySelectorAll('input[type="radio"]') .forEach(function(radio){ let label = document.createElement('label'); let span = document.createElement('span'); label.appendChild(radio.cloneNode()); label.appendChild(span); radio.parentNode.replaceChild(label, radio); }); let labels = document.querySelectorAll('label'); console.log(labels[0].innerHTML, labels); 
 <html> <body> <input type="radio" value="1" name="r8"> <input type="radio" value="2" name="r8"> <input type="radio" value="3" name="r8"> <input type="radio" value="4" name="r8"> </body> </html> 

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