0

html:

    <ul id="box">
        <li><img src="image/i1.png" alt=""></li>
        <li><img src="image/i2.png" alt=""></li>
        <li><img src="image/i3.png" alt=""></li>
    </ul>

script:

    var mybox = document.getElementsByTagName("li");
    document.write(mybox[1].innerHTML);

image/i2.png will be displayed on the webpage,how to get the html string literally?

What i expect to get is the following string.

<li><img src="image/i2.png" alt=""></li>

3 Answers 3

1

Try outerHTML instead. Like This:

var mybox = document.getElementsByTagName('li');
console.log(mybox[0].outerHTML);
<ul id="box">
    <li><img src="image/i1.png" alt=""></li>
    <li><img src="image/i2.png" alt=""></li>
    <li><img src="image/i3.png" alt=""></li>
</ul>

Sign up to request clarification or add additional context in comments.

Comments

0

Use outerHTML to get the element as a whole with the selected tag and it's child element.

var mybox = document.getElementsByTagName("li");
for(var i=0; i<mybox.length; i++){
  console.log(mybox[i].outerHTML);
}
<ul id="box">
    <li><img src="image/i1.png" alt=""></li>
    <li><img src="image/i2.png" alt=""></li>
    <li><img src="image/i3.png" alt=""></li>
</ul>

The outerHTML attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string.

Comments

0

My understanding is that you are trying to display HTML code as string in your document, right ?

You will need to convert special characters like < and > to HTML entities.

To do that, you can use this utility function from https://css-tricks.com/snippets/javascript/htmlentities-for-javascript/

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

to get what you want

document.write(htmlEntities(mybox[1].outerHTML));

demo: https://jsfiddle.net/jacobgoh101/o5s02t2y/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.