1

Is there a easy way to get an array out of a string (html) with jquery/javascript like:

html:

<h1>this is a test</h1>
<p>This is a test</p>
<p>This is a test</p>
<h2>this is a test</h2>
<p>This is a test</p>

to an array:

array[0]['tag'] = 'h1'
array[0]['value'] = 'this is a test'
array[1]['tag'] = 'p'
array[1]['value'] = 'this is a test'
array[2]['tag'] = 'p'
array[2]['value'] = 'this is a test'
array[3]['tag'] = 'h2'
array[3]['value'] = 'this is a test'
array[4]['tag'] = 'p'
array[4]['value'] = 'this is a test'

Thanks!

3 Answers 3

2

updated

JS

var htmlstring = "<h1>this is a test</h1><p>This is a test</p><p>This is a test</p><h2>this is a test</h2><p>This is a test</p>",
    map = { };

$(htmlstring).each(function(_, node) {
    map[ _ ] = { };
    map[ _ ][ node.nodeName ] = node.textContent;
});

console.log(map);

Demo: http://jsfiddle.net/KzfpK/

Sign up to request clarification or add additional context in comments.

2 Comments

But the html is in a string. And not yet an existing element.
@Jaap: updated, you can just wrap a "valid" htmlstring into the jquery constructor aswell.
2

something like this should do the trick but it will not work recursively (only for direct body children).

var tags = [];

$('body').children().each( function( index, element ) {
    tags.push({ 
        'tag' : element.nodeName.toLowerCase(), 
        'value' : element.text()
    });
});

3 Comments

But the html is in a string. And not yet an existing element.
just pass the string into the $() selector then, e.g $('<body><h1>text</h1></body>').children()
@Jaap make it to an jquery object then: $(htmlString) and run both scibuff and @jAndy´s code.
0

here an idea

$('body *').each(function(i){
console.log($(this).text());
console.log(this.nodeName);
console.log(i);
});

1 Comment

beware: using the * can be very slow

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.