简体   繁体   English

jQuery:获取 html 元素的普通 JS 格式

[英]jQuery: get the normal JS format of a html element

I am using jQuery and everything works fine except a few stuff.我正在使用 jQuery,除了一些东西外,一切正常。 There are a few things you cannot do with the jQuery format of an element but only with the simple JS format.有一些事情你不能用元素的 jQuery 格式,而只能用简单的 JS 格式。 Especially, when using the hasAttributes() in simple JS.特别是在简单的 JS 中使用hasAttributes()时。

This works:这有效:

 let fooDiv = document.getElementsByTagName("div")[0]; console.log(fooDiv.hasAttributes()); //returns false as expected let barDiv = document.getElementsByTagName("div")[1]; console.log(barDiv.hasAttributes()); //returns true as expected
 <div>foo</div> <div id="id">bar</div>

This doesn't:这不会:

 let fooDiv = $(document.getElementsByTagName("div")[0]) //creates a jQ object console.log(fooDiv.hasAttributes()); //error let barDiv = $(document.getElementsByTagName("div")[1]) //creates a jQ object console.log(barDiv.hasAttributes()); //error
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div>foo</div> <div id="id">bar</div>

I am aware that the jQuery hasAttr() exists but I want to get the JS format of a jQuery object.我知道 jQuery hasAttr()存在,但我想获取 jQuery 对象的 JS 格式。 There are a lot of differences, for example the jQuery creates an object but otherwise it is a html node list.有很多不同之处,例如 jQuery 创建一个object ,否则它是一个 html 节点列表。

Initially, my question is:最初,我的问题是:

How do I get the html node list or html element or the simple JS format of a html element(s) from jQuery?如何从 jQuery 获取 html 节点列表或 html 元素或 html 元素的简单 JS 格式?

To expand on what blex said in the comments ... when jQuery is used to select an HTML element, the raw HTML is always collected in an array as part of the variable you assign it to.为了扩展 blex 在评论中所说的内容......当使用 jQuery 选择一个 HTML 元素时,原始 HTML 总是作为您分配给它的变量的一部分收集在一个数组中。 For example, using your code:例如,使用您的代码:

// grab the element or elements
let fooDiv = $(document.getElementsByTagName("div")[0]);

// lets see the HTML!
consoe.log( fooDiv[0] ); 

The HTML itself will be exposed in that array, allowing direct access to the HTML and its properties... for example: HTML 本身将在该数组中公开,允许直接访问 HTML 及其属性......例如:

console.log( fooDiv[0].innerHTML );

or或者

console.log( fooDiv[0].tagName );

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

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