4

I have a String which contains HTML tags:

var str = "Hello World <br><p>1</p><em>My First Javascript</em>";

And i also have a form with hidden input:

<input type='hidden' name='id' value=''>

With that String above, i want to get the value inside <p> tag which is 1 and assign that value to hidden input. And after that, i wanted to remove all the HTML tag inside the string which are these <br><p>1</p><em>My First Javascript</em>. So therefore the only value of str will be Hello World.

Is there any way how to do this on Javascript or jquery?

Thanks guys!

PHP Noob
  • 1,597
  • 3
  • 24
  • 34

2 Answers2

4

So, what you want to be doing is to convert your string into a jQuery object. You can do so like this -

var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
var $holder = $('<div>');
$holder.append(str);

Now we have your string encapsulated within another div element. Next we extract the value within the <p> element -

var value = $holder.find('p').text(); // 1

Now that we have that value we can place it into the hidden input field -

$('input[name="id"]').val(value);

Now to remove all other elements from the original string - we'll use the container we created earlier for this -

$.each($holder.children(),function(index,elem){
  $(elem).remove();
});

Now we can take the textual contents of $holder with $holder.text() and it should be just -

Hello World


If you would like to fiddle with this,
you can do so here - http://jsfiddle.net/TVXbw/1/

Lix
  • 47,311
  • 12
  • 103
  • 131
0

Ok, a quick and simple way:

var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = str;//where str is the html string, obviously...
var pTagValue = tmpDiv.getElementsByTagName('p')[0].innerHTML;//=== '1'
document.getElementById('yourInputId').value = pTagValue;

If I understood correctly, that's what you're after, right?

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • Half way - what about emptying the contents of the original `str` down to only `"Hello World"`? – Lix Jul 15 '12 at 14:14
  • just use the `childNodes[0].textContent`, the `childNodes` nodelist (!== Array) returns both html elements and textnodes, if an element of this list hast the propery `textContent`, you're dealing with... text, that isn't contained in any sort of special tag – Elias Van Ootegem Jul 15 '12 at 14:21