简体   繁体   中英

Can not get innerHTML from a jQuery Object

I am using google map api. I wrote the code below.

<div id="map"></div>

And I use the google chrome console to see the content of $("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 :

<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?

Thank you very much.

To get a plain javascript dom object from a valid jquery selector, use get(0) or [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

$("#map")[0].innerHTML

Although an easier way, since you are already using jQuery, would be to use jQuery's version of innerHTML html .

$("#map").html()

As for your second question, you can insert a div into the div like this:

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);

Use the html() method to get the html from a jQuery object.

console.log($("div#map").html());

http://api.jquery.com/html/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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