0

I have a string that looks like this:

my_str = "<h1>title</h1><p>parag1</p><p>parag2</p> (more paragraphs)";

I'd like to create two arrays : arr_tags (contains 'h1', 'p', 'p') and arr_contents (contains 'title', 'parag1', 'parag2').

I first thought "splice" and "split" methods, but I do not see how.

4 Answers 4

1

One more version with .each(), .prop() and .text():

var my_str = "<h1>title</h1><p>parag1</p><p>parag2</p>";
var arr_tags = [];
var arr_contents = [];

$(my_str).each(function()
{
    arr_tags.push($(this).prop("tagName"));
    arr_contents.push($(this).text());
});

console.log(arr_tags);
console.log(arr_contents);

Fiddle.

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

2 Comments

Beat me to it :P I did this! Only I used arr_tags.push(this.nodeName)
@Mardoxx I usually end up with such thoughts. But not this time :)
0

This is pretty easy if you indeed use jQuery, it has a map function for this:

$(function () {
    var my_str = "<h1>title</h1><p>parag1</p><p>parag2</p>";

    var $tags = $(my_str).map(function() {
        return this.tagName;
    }).get();

    var $texts = $(my_str).map(function() {
        return $(this).text();
    }).get();

    console.log($tags);
    console.log($texts);
});

Fiddle

Comments

0

Use jQuery.parseHTML:

var html = $.parseHTML("<h1>title</h1><p>parag1</p><p>parag2</p>");
$.each(html, function(i, el ) {
  console.log(el);
  console.log(el.nodeName)
});

Comments

0

The non-jQuery answer.

var tags = document.createElement('div');
tags.innerHTML = my_str;

var children = [].slice.call(tags.children);
var elements = children.map(function(child) {
  return child.tagName;
});
var contents = children.map(function(child) {
  return child.textContent;
});

Comments

Your Answer

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