使用JavaScript,如何判断DOM中的HTML对象是否不在HTML源代码中?

StackOverflow https://stackoverflow.com/questions/6047064

  •  15-11-2019
  •  | 
  •  

我正在寻找关于如何检测HTML DOM中的对象的想法,但它们不是在HTML源中明确表示的。

您可能知道,如果我有包含以下内容的HTML源:

<table id="myTbl">
    <tr id="row1">
        <td id="name">George</td>
    </tr>
</table>
.

... HTML DOM将在对象树中添加<tbody>对象而不更改源代码,了解源代码意味着它。所以在DOM中,结构就好像HTML源已经是:

<table id="myTbl">
    <tbody>
        <tr id="row1">
            <td id="name">George</td>
        </tr>
    </tbody>
</table>
.

我有一个浏览DOM树的JavaScript函数,我需要检测我何时遇到暗示的对象,即它位于DOM中,但不在HTML源中。

任何想法如何做到这一点?也许在对象中有一些属性,可以讲述它是否源于源?

有帮助吗?

解决方案

New idea based on Alex's idea. Still involves re-fetching the entire DOM, but it's impossible to do otherwise. You could implement this same logic server-side if it's feasible in your app. Using jQuery for brevity:

function getInsertedElements(callback){
    $.get('.', function(content){
        callback($(content
            .replace(/(<\w+[^>]+class\s*=\s*")/gi, '$1from-source ')
            .replace(/(<\w+)(?![^>]* class\s*=)/gi, '$1 class="from-source"')
        ).find(':not(.from-source)'));
    });
}

that will give you a list of all elements inserted :) May need some refinement , e.g. around the quotes matching class=" since a quote is technically optional there. Also un-tested, but should work.

Note that you're getting new elements back with this method, not the ones that currently exist in your DOM, so if that matters just be aware of it.

其他提示

Reading your comment you just need to determine if a <tbody> tag has been added by the rendering process as opposed to being present in the source?

If so why not modify the source that does contain <tbody> by applying an attribute <tbody class="exp">, then as you walk the DOM you know that any tbody node not possessing that attribute was inserted by the rendering engine.

May be keep at the document.body.onload the string of the initial document.body.innerHTML

Then when you want to make the check, test first to see if they are still the same.
If not compare both strings and find the differences.

I guess this is ok, if you don't have a too heavy page.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top