Home > Software engineering >  How do I convert HTML code into a JavaScript String variable?
How do I convert HTML code into a JavaScript String variable?

Time:03-05

I am wondering how I can convert my HTML code that has been garbed with my document.getElementById("landornot") function and convert it into a string. For example right now when I console.log it I get <li id="landornot"><span >Property Type: </span><a href="https://axisutahdev.wpengine.com/property-types/land/" rel="tag">Land</a></li>

What I want is it to be in a string so it should look like this '<li id="landornot"><span >Property Type: </span><a href="https://axisutahdev.wpengine.com/property-types/land/" rel="tag">Land</a></li>'

I haven't been able to find any helpful resource online any help would be appreciated.

My Code:

<script>
    window.onload = (event) => {
        const land = document.getElementById("landornot");
        console.log(land);
        
        if (land === '<li  id="landornot"><span >Property Type: </span><a href="https://axisutahdev.wpengine.com/property-types/land/" rel="tag">Land</a></li>') {
            console.log('Right Page')
        } else {
            console.log('Wrong Page')
        }
    };
</script>

CodePudding user response:

Have you tried using the .outerHTML property? E.g. console.log(land.outerHTML);

CodePudding user response:

    <script>
        window.onload = (event) => {
            const land = document.getElementById("landornot");
            land = land.outerHTML;
            console.log(land);
            
            if (land === '<li  id="landornot"><span >Property Type: </span><a href="https://axisutahdev.wpengine.com/property-types/land/" rel="tag">Land</a></li>') {
                console.log('Right Page')
            } else {
                console.log('Wrong Page')
            }
        };
    </script>

you need element.outerHTML

CodePudding user response:

Maybe you can use the built in function: Tostring()

  • Related