3

I need to change a tag for another tag with the same properties. For example change this:

<TagOne width="500" height="200">asdfasdf</TagOne>

to this:

<AnotherTag width="500" height="200">sometext</AnotherTag>

With this code I can see the attributes but i don't know how to replace the tag for the other one:

const htmlparser2 = require("htmlparser2"); 
const DomUtils = require("htmlparser2").DomUtils;  
const htmlContent = `<html>
<head></head> <body>    <div id="content">
 <TagOne width="500" height="200" src="image1.jpg">asdfasdf</TagOne>
   <p>asdfasdf</p>   </div></body></html>`; const parser = new htmlparser2.Parser(
   {
        onopentag(name, attribs) {
          if (name === "TagOne") {
                 if(attribs.width ){
                    var width = attribs.width;
                }
                if(attribs.height ){
                    var height = attribs.height; 
                }
                var new_tag = `<AnotherTag width:`+width+`; height:`+height+`;">sometext</div>`;


            }
        },
        ontext(text) {
             console.log("-->", text);

         },
         onclosetag(tagname,new_tag) {
             if (tagname === "amp-iframe") {
                 console.log("That's it?!");

             }
         },
     },
     { decodeEntities: true } ); 
 var content = parser.write(htmlContent); 
 parser.end();

I have tried to do this on the onclosetag function:

  //htmlparser2.DomUtils.removeElement(tagname);
     //parser.write(new_tag);

but it gives me an error, it is not the correct way but I can't find anything similar in the documentation. can someone help me? Thanks.

J. Alan
  • 51
  • 2

0 Answers0