0

I'm having trouble with getting texts that are in element to array. The structure I'm trying to 'extract' is looking something like this:

<div>
    text text text text
    <h2> title </h2>
    text2 text2 text2
    <img>
    <br>
    <br>
    text3 text3 text3 
    <h2> title 2</h2>
    text4 text4 text4
</div>

the result I'm looking for is array:

['text text text', 'text2 text2 text2', 'text3 text3 text3', 'text4 text4 text4']

I can't edit the HTML structure. And I don't have idea how to get this data to an array. I've only tried .text() from jquery, but that's not the way, and I didn't found anything in google, that would help.

3
  • 1
    Thanks for the information on what you're doing. I'm assuming you have a problem though. Please enlighten us with the problem :-p Commented Nov 18, 2013 at 11:52
  • Put your text into a tag like <span>text text text</span> then something like var array = $("span").split(" "); Commented Nov 18, 2013 at 11:54
  • Do you have control over the generated html elements? Commented Nov 18, 2013 at 11:55

1 Answer 1

3

You can use .contents() and .map() to create a solution

var arr = $('div').contents().map(function () {
    if (this.nodeType == 3) {
        var text = $.trim(this.nodeValue);
        if (text != '') {
            return text
        }
    }
}).get();

console.log(arr)

Demo: Fiddle

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.