Load static HTML file and split into array by class

时间:2016-04-04 18:14:25

标签: javascript jquery html

I have been working on this for days and I get close but not all the way. Most of the SO answers I have found, help me get the file contents loaded into a div or a variable but it doesn't let me then do querySelectorAll on it. So, what I need to do is load the file and then break it up into an array based on a class. Without further ado, the code:

content.txt:

<h3 class="chapter">Chapter 1</h3>
<p>Lorem</p>
<h3 class="chapter">Chapter 2</h3>
<p>Lorem</p>

Loading JS:

$.ajax({
      url: "content/content.txt",
      cache: false,
      crossDomain: true,
      success: function(html){          
        var div = document.createElement("div");
        div.innerHTML = html;
        var chapters = div.querySelectorAll('chapter');
        alert(chapters.length);

      }
    }); 

Expected Result:

['<h3 class="chapter">Chapter 1</h3><p>Lorem</p>',
  '<h3 class="chapter">Chapter 2</h3><p>Lorem</p>']

So this loads the file (confirmed) and I have the html in a variable. I try loading it into a dynamic DIV in the DOM to do a querySelectorAll but all it returns is {}. If I dump the innerHTML all of my content is there.

I know I am mixing vanilla JS with jQuery, but I am unsure of the proper jQuery way to go about this. Any thoughts?

1 个答案:

答案 0 :(得分:3)

The selector chapter will match all your <chapter> elements. There is no such element in HTML and there is no such element in your text file. That is why nothing matches.

align="chapter" is invalid HTML. chapter is not a valid value for the align attribute, which is obsolete anyway.

Start by writing sensible HTML. Use a class to distinguish between types of div elements.

<div class="chapter">

For that matter, consider using the <section> element instead.

Then use a class selector (instead of a type selector):

div.querySelectorAll('.chapter');