Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 512
user1836330 Avatar asked Nov 23 '12 19:11

user1836330


1 Answers

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);
like image 82
Travis J Avatar answered Sep 19 '22 12:09

Travis J