0

There's a similar thread here, but it only deals with parsing Element-only HTML strings.

How to get an HTML element from a string with jQuery

In my case, I have an HTML string combining plain text with element(s).

var str = 'Some text ' + 
          '<input type="hidden" id="hiddenField" value="3" /> ' +
          '<input type="text" id="textField"/>';

I need the following 2 functions, (1) Extract Plain Text from this string, (2) Extract Element by ID.

Examples:

(1) getText(str) => 'Some text ';

(2) getElement(str, id) => jQuery element variable

I was going to split by ID, and then split by </> multiple times, then stitch together different strings, but that doesn't seem elegant, wondering if there are better ways.

gene b.
  • 10,512
  • 21
  • 115
  • 227
  • 1
    In your case, can you modify the HTML you want to manipulate ? Because if you wrap your HTML/plain text with a `
    ` (for example), you can easily extract what you want with Jquery.
    – Ugo T. May 13 '19 at 15:18

2 Answers2

1

For the first requirement, just strip all the html from your string, you can do it using regex:

var stripedHtml = str.replace(/<[^>]+>/g, '');
console.log(stripedHtml) //Some text 

Here is a working example

For the second use case, just parse it as html element and you're ready to go.

var el = document.createElement( 'html' );
el.innerHTML = 'Some text ' + 
          '<input type="hidden" id="hiddenField" value="3" /> ' +
          '<input type="text" id="textField"/>';

el.getElementsByTagName( 'input' )

See here a working example for the second scenario.

Alon Adler
  • 3,984
  • 4
  • 32
  • 44
0

var str = 'Some text ' + 
          '<input type="hidden" id="hiddenField" value="3" /> ' +
          '<input type="text" id="textField"/>';
          
str2=str.split("<")        
          
          
for(i = 1; i < str2.length; i++){
   str2[i] = "<" + str2[i]
}

getID = document.getElementById("hiddenField")
     
console.log(getID)
<input type="hidden" id="hiddenField" value="3" /> 
<input type="text" id="textField"/>
DCR
  • 14,737
  • 12
  • 52
  • 115