jQuery: how to change tag name?

前端 未结 17 920
無奈伤痛
無奈伤痛 2020-11-28 07:37

jQuery: how to change tag name?

For example:


    $1

I need

$1
<
17条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 08:28

    Simply changing the property values won't do it (as others have said, some HTMLElement properties are read-only; also some hold prototypal context to more primitive elements). The closest thing you can get to mimicking the DOM API is to mimic also the process of prototypal inheritance in JavaScript.

    'Setting' on an object's prototype via __proto__ is generally frowned upon. Also, you might consider why you think you need to duplicate the entire DOM element in the first place. But here goes:

    // Define this at whatever scope you'll need to access it
    // Most of these kinds of constructors are attached to the `window` object
    
    window.HTMLBookElement = function() {
    
      function HTMLBookElement() {
        var book = document.createElement('book');
        book.__proto__ = document.createElement('audio');
        return book;
      }
    
      return new HTMLBookElement();
    
    }
    
    // Test your new element in a console (I'm assuming you have Chrome)
    
    var harryPotter = new HTMLBookElement();
    
    // You should have access to your new `HTMLBookElement` API as well as that
    // of its prototype chain; since I prototyped `HTMLAudioElement`, you have 
    // some default properties like `volume` and `preload`:
    
    console.log(harryPotter);         // should log ""
    console.log(harryPotter.volume);  // should log "1"
    console.log(harryPotter.preload); // should log "auto"
    

    All DOM elements work this way. For example:

    is produced by HTMLDivElement, which extends HTMLElement, which in turn extends Element, which in turn extends Object.

提交回复
热议问题