How to convert an html string to jQuery object?

Asked

Viewed 1,853 times

8

How to convert a string HTML in a jQuery object?

var objeto = '<div id="minhaDiv"><span id="meuSpan">Span</span></div>';
  • Can you better explain what you want to have/do with this jQuery object? (to be clearer what you are looking for)

  • @Sergio I have an AJAX call that returns a string that will be inserted into my DOM. I would like to do a search (using find) before adding it to the DOM instead of adding and having to do the search in the entire DOM.

2 answers

11


Very simple, just instate jQuery by passing HTML as parameter.

var teste = $('<div id="minhaDiv"><span id="meuSpan">Span</span></div>').find("span").text();
$("#result").html(teste);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>

8

You can use innerHTML native. Example

var objeto = '<div id="minhaDiv"><span id="meuSpan">Span</span></div>';
document.getElementById("ID_DIV").innerHTML = objeto ;

Or you can use JQuery:

var objeto = '<div id="minhaDiv"><span id="meuSpan">Span</span></div>';
$("#ID_DIV").html(objeto );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.