Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a HTML element from a string with jQuery

People also ask

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.

How HTML elements are used in jQuery with example?

The html() method in jQuery is used to get the contents of the first element in the set of matched elements or is used to set the HTML contents of every matched element. It returns the content of the first matched element. This function does not accept any arguments.


Yes, you can turn the string into elements, and select elements from it. Example:

var elements = $(theHtmlString);
var found = $('.FindMe', elements);

Just wrap the html text in the $ function. Like

$("<div>I want this element</div>")

If you are loading a page dynamically from a server then you can target just one element from the loaded page using the following form with .load()

$(selectorWhereToShowNewData).load('pagePath selectorForElementFromNewData');

For example:

$('#result').load('ajax/test.html #container');

Where:
#result is where the loaded page part will be displayed on the current page
ajax/test.html is the URL to which the server request is sent
#container is the element on the response page you want to display. Only that will be loaded into the element #result. The rest of the response page will not be displayed.


Just use $.filter

var html = "<div><span class='im-here'></span></div>"
var found = $(html).filter(".im-here")

You can use $.find

$(document).ready(function() {
  var htmlVal = "<div><span class='im-here'>Span Value</span></div>";
  var spanElement = $(htmlVal).find("span");
  var spanVal = spanElement.text();

  alert(spanVal);
});