javascript 无法从 jQuery 对象获取 innerHTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13534617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can not get innerHTML from a jQuery Object
提问by user1836330
I am using google map api. I wrote the code below.
我正在使用谷歌地图 API。我写了下面的代码。
<div id="map"></div>
And I use the google chrome console to see the content of $("div#map")
.
我使用谷歌浏览器控制台查看$("div#map")
.
console.log($("div#map"));
The result is:
结果是:
[
<div id=?"map" style=?"width:? 1218.222222328186px;? position:? relative;? background-color:? rgb(229, 227, 223)?;? overflow:? hidden;? -webkit-transform:? translateZ(0)?;? ">?
<div style=?"position:? absolute;? left:? 0px;? top:? 0px;? overflow:? hidden;? width:? 100%;? height:? 100%;? z-index:? 0;? ">?…?</div>?
</div>?
]
How can I get the innerHTML :
我怎样才能得到innerHTML:
<div style=?"position:? absolute;? left:? 0px;? top:? 0px;? overflow:? hidden;? width:? 100%;? height:? 100%;? z-index:? 0;? ">?…?</div>?
I tried $("div#map > div")
, but there is nothing returned.
Why? Is it because the innerHTML generated by Javascript?
How can I get it and insert another div into the div above?
我试过了$("div#map > div")
,但没有任何回报。为什么?是不是因为Javascript生成的innerHTML?我怎样才能得到它并将另一个 div 插入上面的 div 中?
Thank you very much.
非常感谢你。
回答by Travis J
To get a plain javascript dom object from a valid jquery selector, use get(0)
or [0]
.
要从有效的 jquery 选择器中获取普通的 javascript dom 对象,请使用get(0)
或[0]
。
$("#map")[0]//note that as id's are unique, you do not need to have anything else
//in here to target them
Once you have the plain DOM object, you can use innerHTML
一旦你有了普通的 DOM 对象,你就可以使用 innerHTML
$("#map")[0].innerHTML
Although an easier way, since you are already using jQuery, would be to use jQuery's version of innerHTML html
.
虽然更简单的方法是,因为您已经在使用 jQuery,但是使用 jQuery 的 innerHTML 版本html
。
$("#map").html()
As for your second question, you can insert a div into the div like this:
至于你的第二个问题,你可以像这样在 div 中插入一个 div:
var newDiv = document.createElement("div");
newDiv.innerHTML = "simple text, probably want to make more elements and set attributes and build them using .appendChild().";
$("#map")[0].appendChild(newDiv);
Or like this for the parent of map:
或者像这样对于地图的父级:
$("#map")[0].parentNode.appendChild(newDiv);
回答by Nathan Wall
Use the html()
method to get the html from a jQuery object.
使用html()
方法从 jQuery 对象获取 html。
console.log($("div#map").html());