How to get element from innerHTML?

35
October 22, 2019, at 1:30 PM

I am trying to access element from another element's innerHTML. I have this element:

I can clearly see the element I need inside of it. However, when I try to do this:

$chartContainer.find(".pin")

It is not found. What is the problem here?

Answer 1

You can see from the log output that $chartContainer is a HTMLDivElement object, not a jQuery object. Therefore calling find() on it directly will not work. The $ prefix on the variable name is confusing matters, so I would suggest removing it.

To fix the problem you need to wrap the $chartContainer in a jQuery object:

var $pin = $($chartContainer).find(".pin");
Answer 2

There are so many ways to get info about your elements.

Using the innerHTML as identifier is not a good solution.

You probably need some sort of event to that makes you search for that "Menu1"

So here is a click handler that works also on other events that give you information about what you have clicked.

function handler(e){
 var txt='You clicked on a '+e.target.nodeName+'\n';
    txt+='The innerHTML is '+e.target.innerHTML+'\n';
    txt+='The text is '+e.target.textContent+'\n';
    txt+='The parentNode is '+e.target.parentNode.nodeName+'\n';
 alert(txt)
}
document.addEventListener('click',handler,false)

DEMO

http://jsfiddle.net/a4J9U/

If you want that your script searches for that "Menu1" you should consider adding that "Menu1" as an attribute on the span or parentNode.

<div id="Menu1">
 <span>Home1</span>
</div>

and then call

document.getElementById('Menu1');

which is very fast.

If you explain more specifically why you need to get that span from a variable I can re-elaborate the code.

if you have any questions just ask.

READ ALSO
&ldquo;Loading leaks&rdquo; on LeakCanary is really slow, what alternatives do I have?

“Loading leaks” on LeakCanary is really slow, what alternatives do I have?

Every time I want to look into a leak, I click on the notification of the leak and it takes a really long time to load, like enough time that I usually forget about it

33
Created object in React Native is moving on IOS but not Android

Created object in React Native is moving on IOS but not Android

I am new to react native and I'm having a little trouble getting the created ball object to move in androidThe code I have now properly moves the object by dragging it on the screen with one finger in IOS

47
Android: Increase Geofences accuracy

Android: Increase Geofences accuracy

I'm building an app using Geofences, right now the minimum radius I can set so my geofence can get accurately detected is 30mI want to be able to set a minimum radius of 5m

23
How to send files to flutter app via sharing?

How to send files to flutter app via sharing?

I want my flutter application to accept Videos and Images when shared by other appsFor eg

54