How to find if element with specific id exists or not

前端 未结 6 1915
独厮守ぢ
独厮守ぢ 2020-12-08 04:18

In my JavaScript I want to check whether the element with specific id is exist or not, I tried it with 2 ways

1).

var myEle = document.getElementByI         


        
6条回答
  •  感情败类
    2020-12-08 05:08

    document.getElementById('yourId')
    

    is the correct way.

    the document refers the HTML document that is loaded in the DOM.

    and it searches the id using the function getElementById() which takes a parameter of the id of an element

    Solution will be :

    var elem = (document.getElementById('myElement'))? document.getElementById('myElement').value : '';
    
    /* this will assign a value or give you and empty string */
    

提交回复
热议问题