2

I have an javascript array that is hard coded into my javascript file:

var avatar_layers = new Array('background', 'body', 'hair', 'shirt', 'arms', 'legs', 'feet', 'weapon')

As it is hardcoded, it is difficult to use it between different HTML files.

I would like to change it so the javascript will look for all the h3 tags that have a class of title on the page and use the content of these tags to create the array.

How can I do this?

After reading around, I have found that I should use the following

document.getElementsByTagName("h3.title")[0];

This will get all the h3.titles. However, I am not sure how to output the collected data as array.

I would really appreciate any pointers. Thanks!

Update: I can't use Jquery, it has to be regular java script

You can see my code here: http://jsfiddle.net/zk5Hn/2/

4
  • what do you mean by "output data as array"? output where? in console? Commented Sep 25, 2012 at 14:06
  • @gryzzly The array I have posted is used later on in the script. So I want the values of the array to come from the HTML in my page. Is that possible? Commented Sep 25, 2012 at 14:09
  • Sure it is. You want to store the titles from HTML in an array? Is that correct? Commented Sep 25, 2012 at 14:09
  • @grryzzly Yes, that's correct. Commented Sep 25, 2012 at 14:11

7 Answers 7

3
​var array = [];

(function(){
    var elements = document.getElementsByTagName("h3");
    for (var i = 0; i < elements.length; i++) {
        array.push(elements[i].innerText);
    }
})();

​alert(array);​

try that.

http://jsfiddle.net/Jsckt/

alternatively you could use jquery:

$(function(){
    var array = [];

    $("h3.title").each(function() {
        array.push(this.innerText);
    });

    alert(array);
}​;​

http://jsfiddle.net/Jsckt/2/

5 years later edit:

  1. one should avoid using innerText theese days for performance and expectational reasons
  2. you can explode DOM node lists to arrays now

there you go with a up2date solution for 2018 onwards:

const headings = [...document.querySelectorAll("h3.title")].map(node => node.textContent);
alert(headings);
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your help! I tried that but it doesn't work. Here is my code before I made any modifications: jsfiddle.net/zk5Hn/2 Here is my code afterwards: jsfiddle.net/qrSEM. Am I doing something wrong?
doesnt run because you run it before the html is loaded.
you srsly should use jquery cause there you only need to do: $(function(){/*content here*/}); to fire it when the dom is ready to be modified
jsfiddle.net/hkuVM/1 there. an update to your code. (just modified it on the right side so it runs when the dom is ready)
Yes, you are right about Jquery. I think I'm going to redo the project and use it. It is a big time saver. Thanks for your help.
|
2

Something like:

var titles = document.querySelectorAll('.title'),
    avatar_layers = [];
for( var i=0; i<titles.length; i++ ) {
    avatar_layers.push( titles[i].innerHTML );
}

It will create a new, empty array. Then look inside all elements that has the class .title and extract it’s HTML content. Then push this content into the array.

Using jQuery it would be very simple:

var avatar_layers = $('.title').map(function(){
    return $(this).html();
});

Is this what you want?

Note that querySelectorAll is not supported in IE7-, so you’ll need a library like jQuery or some other workaround if you need support for those browsers.

Comments

2

No, document.getElementsByTagName will not apply the class selector, you'd need to use document.querySelectorAll for that (and because it is not supported by legacy browsers like IE, you might need to use a selector library or some other workarounds).

Then, you got a NodeList back which already is like an array of elements. Iterate over it and add the contents of each element to your array:

var headingEls = document.querySelectorAll("h3.title");
var avatar_layers = []; // empty array literal
for (var i=0; i<headingEls.length; i++)
    avatar_layers.push(headingEls[i].textContent);

Don't forget that you can access the elements not until the DOM is loaded, you will need to execute that snippet on a domready event; you can't use the array immidiately.

Comments

1
var h3s = document.getElementsByTagName("h3");

var arr = [].map.call(h3s, function(el) {
                              return el.textContent || el.innerText;
                           });

You can get a patch for .map in old browsers here: MDN .map

Comments

1

If you are using jQuery then,

var titleArray = new Array();
$('h3.title').each(function(){
    titleArray.push($(this).text());
});

alert(titleArray);

Demo: http://jsfiddle.net/muthkum/WVsEB/3/

1 Comment

Thanks for your help. However, I can't use jqeury for this project!
1

Older versions of Javascript haven't a nativ method to select elements by the attribute 'class'. In the past I found a selfcreated method to fill that gap. You can find the workaround here . This function does work for IE6 either

3 Comments

Thanks for the reply. I tried that code in the link, but it doesn't seem to work. Here is my code before: jsfiddle.net/zk5Hn/2 and after: jsfiddle.net/33Lyb Could you give me some pointers? Thanks!
What exactly does not work? The method to find tags with class attribute?
The class works. you made a mistike in defining the variable scope. The definition of variable 'avatar_layers' must be moved into the global scope and not within a function. The call of ..ByClass() either.
0
<h3 class = 'title'>trtr</h3>
<h3 class = 'title'>tcrtr</h3>
<h3 class = 'title'>tdrtr</h3>
<h3 class = 'title'>trrtr</h3>
<h3>trgtr</h3>

var arrayDemo  = [];
$.each($('h3[class*=title]'), function () {
         arrayDemo.push(this.innerHTML);
});

alert(arrayDemo);

Here is the demo for this http://jsfiddle.net/ymtFg/

2 Comments

This assumes you will be using Jquery Library
Oh That's why it wasn't working. I can't use Jquery for this!

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.