简体   繁体   English

如何检查我的DOM是否已包含ID的元素?

[英]How can i check if my DOM already contains an element by id?

I would like to know if it is possible to check if my DOM contains an element id. 我想知道是否可以检查我的DOM是否包含元素ID。 Actually I dynamically load my templates (kendo templates) and append them in my body. 实际上,我会动态加载我的模板(剑道模板)并将其附加到我的体内。

<body>
    ...

    <script type="text/x-kendo-template" id="test-view">
        ...
    </script>
</body>

At this moment my loading script is 目前,我的加载脚本是

//Creates a gloabl object called templateLoader with a single method "loadExtTemplate"
var templateLoader = (function ($, host) {
    //Loads external templates from path and injects in to page DOM
    return {
        //Method: loadExtTemplate
        //Params: (string) path: the relative path to a file that contains template definition(s)
        loadExtTemplate: function (path) {
            //Use jQuery Ajax to fetch the template file
            var tmplLoader = $.get(path)
                .success(function (result) {
                    //On success, Add templates to DOM (assumes file only has template definitions)
                    var regSplit = new RegExp("[/\]+", "g");
                    var pathTab = path.split(regSplit);
                    var templateName = pathTab[pathTab.length - 1];
                    var regReplace = new RegExp("[.]+", "g");
                    var templateName = templateName.replace(regReplace, "-");
                    var s = $("<script type=\"text/x-kendo-template\" id=\"" + templateName + "\">" + result + "</script>");
                    $("body").append(s);
                })
                .error(function (result) {
                    alert("Error Loading Templates -- TODO: Better Error Handling");
                })

            tmplLoader.complete(function () {
                //Publish an event that indicates when a template is done loading
                $(host).trigger("TEMPLATE_LOADED", [path]);
            });
        }
    };
})(jQuery, document);

Before loading my template I need to check if this one is already loaded. 在加载模板之前,我需要检查该模板是否已经加载。 I need to check if a script with the id="test-view" exists or not. 我需要检查是否存在具有id =“ test-view”的脚本。 How can I do that? 我怎样才能做到这一点?

var elementExists = (document.getElementById("elementId") !== null);

现在, elementExists将包含一个布尔值,该布尔值告诉您该元素是否已经存在。

var element = $('#' + templateName)
if(!element.length) {
   // create your template
}

I would suggest adding 我建议添加

if(document.getElementById(templateName)) return;

after

var templateName = templateName.replace(regReplace, "-");

So your code becomes: 因此,您的代码变为:

.success(function (result) {
    //On success, Add templates to DOM (assumes file only has template definitions)
    var regSplit = new RegExp("[/\]+", "g");
    var pathTab = path.split(regSplit);
    var templateName = pathTab[pathTab.length - 1];
    var regReplace = new RegExp("[.]+", "g");
    var templateName = templateName.replace(regReplace, "-");
    if(document.getElementById(templateName)) return;
    var s = $("<script type=\"text/x-kendo-template\" id=\"" + templateName + "\">" + result + "</script>");
    $("body").append(s);
})

You can do this using length or size: 您可以使用长度或大小来做到这一点:

eg, 例如,

$("#test-view").length //$("#test-view").size()

With jQuery: 使用jQuery:

if ($("#test-view").length) {...}

Plain JavaScript: 纯JavaScript:

if (document.querySelectorAll("#test-view").length) {...}

And a couple comments: 和一些评论:

  • [html4] id is not a regular attribute for the script tag (but AFAIK all browsers support it) [html4] id不是script标记的常规属性(但AFAIK所有浏览器都支持它)
  • the above code works for any selector, not just ids 上面的代码适用于任何选择器,不仅限于id
  • querySelectorAll is not supported in IE7 IE7不支持querySelectorAll

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM