0

I am working on a project where i need to get a specific element from an external html file as a string in my jQuery.

As i understand the .get(); function cannot get a specific element (by class or ID) and the .load() can, but loads it directly into the dom of the file.

Is there another function or a way to go about this?

What i need to do is get a specific html element and replace some macros in it with data from an object and then append it to an element (multiple times.) Therefore i cannot just load it in and replace the macros afterwards.

1
  • You need to use $.get to retrieve the HTML, and then select the element you want from the returned HTML. This is effectively what load() does, just without the final append operation. Commented Aug 12, 2015 at 9:18

1 Answer 1

2

You can .get it and then only subselect.

$.get('myfile.html', function(response) {
  var inside = $(response).find('#inner-id');
  // do stuff with inside...
});
Sign up to request clarification or add additional context in comments.

5 Comments

I know its an old post but Im interested. I tried this code but I got an error that says inner-id is not defined.
The parameter there is your CSS selector for the item you want to find, in this case, any HTML tag with the id="inner-id" attribute - you can either change the selector argument to something that fits you, or add id="inner-id" to the element you are trying to find
#inner-id must be an element inside myfile.html, right?
Yes, because we are using the find function on the wrapped $(response)
I was doing so but it didnt work. turns out it was a totally different problem all along but thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.