chaining getElementById

前端 未结 6 1703
盖世英雄少女心
盖世英雄少女心 2020-11-29 12:27

I\'ve been looking for an answer to this question but I could find none so I thought I\'d try StackOverflow.

In javascript, is this valid:

x = document

6条回答
  •  半阙折子戏
    2020-11-29 12:52

    You can just use y = x.querySelector('#'+'mySecondId'); instead of y = x.getElementById('mySecondId'); in the sample of the question.

    Element.getElementById doesn't exist but you can add it as mentioned in other answers, even if it is not recommended to add a method to Element. In case you want absolutely use this kind of solution, below is a possibility:

    Element.prototype.getElementById = function(id) {
    return this.querySelector("#"+id);
    }
    

    One advantage to use element.querySelector instead of document.getElementById inside Element.prototype.getElementById is that element.querySelector is working even if the element is not already in the DOM, such as after creating it with document.createElement.

提交回复
热议问题