get opening tag including attributes - outerHTML without innerHTML

后端 未结 7 1344
花落未央
花落未央 2020-12-10 03:22

I would like to retrieve a certain tag element with its attributes from the DOM. For example, from


  link text
         


        
7条回答
  •  长情又很酷
    2020-12-10 03:26

    This can be done without any String manipulation.

    Instead, you can use the element's internals and build the string yourself from there:

    function getTagHTML(el) {
      if (!el instanceof HTMLElement) return null;
      let result = `<${el.tagName.toLowerCase()}`;
      for (const attribute in el.attributes) {
        if (el.attributes[attribute].nodeValue) 
          result += ` ${el.attributes[attribute].name}="${el.attributes[attribute].nodeValue.replace(/"/g, """)}"`
      }
      result += `>`;
      return result;
    }
    
    console.log(getTagHTML(document.getElementById('outer')));
    I do not want this

    Please note that for self-closing elements like this would give you an unwanted and incorrect closing tag. Feel free to adjust the code accordingly.

提交回复
热议问题