codenijuan
codenijuan

Reputation: 35

How to get the HTML tags only from a string

Is it possible to get the HTML tag from a string with jQuery (or plain old JavaScript)?

Example:

var htmltag = "<table><tr><td>sample text</td><td><input type="submit" value="Click"/></td></tr></table>";

The output must like this:

<input type="submit" value="Click"/>

How I can get the HTML tag from a string using jQuery?

Upvotes: 1

Views: 309

Answers (2)

Seth
Seth

Reputation: 1255

As mentioned in the (as of posting this) highest rating answer in the RegEx match open tags except XHTML self-contained tags-Thread it might generally be a bad idea to parse HTML using regular expression. The thread has some interesting bits and pieces so if you are considering using a RegEx to parse some piece of HTML go ahead and read it. Quite a few cases are discussed.

In this example with the exact input from the OP given it does work. Using arbitrary HTML fragments would indeed be a bad idea. Just as an example consider having this field in your HTML <input type='text' value='this is cool :>' /> it would totally mess up the parsing. (Even if it should be a &gt; ... this is the real world, don't expect it to be one). So be very careful and considerate about what you do.

My original answer was:

You could use a regular expression to match what you want. In this case it might look like this:

htmltag.match("<input .*?>");

The result would be an array containing just the input tag

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74410

Wrap your string in jQuery object then use any transversal method on it.

If you want the element as jq object:

var $input = $(htmltag).find('input');

If you want it as string:

var inputHTML = $(htmltag).find('input').prop('outerHTML');

Upvotes: 7

Related Questions