Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementsByClassName > get children

I have this HTML code:

<div id="channels_0">
   <div id="channels">
      <h4 class="date"><span id="date">Sat 22nd Sep</span> @ 
      <span id="time">12:45</span></h4>
      <h3 class="teems"><span id="date">Swansea City v Everton </span></h3>
      <h4 class="tv"><span id="mychannels"></span>Sky Sports 2/Sky Sports 2 HD</h4>
   </div>
</div>

I have this JS:

document.getElementById('channels').innerText)

Which outputs:

Sat 22nd Sep @ 12:45
Swansea City v Everton
Sky Sports 2/Sky Sports 2 HD

How do i get a handle and output the individual items like: mychannels, or teems or time or date i.e. i need to get the children, how is this done?

I have tried:

document.getElementById('channels').getElementsByTagName('date').value; 

and

document.getElementsByClassName('date').value;

and others, but still cant seem to get a handle on it.

like image 375
dmac Avatar asked Sep 20 '12 09:09

dmac


2 Answers

var channels = document.getElementById('channels');

var date = channels.getElementsByClassName("date")[0];
var datePart = date.getElementById("date").innerHTML;
var timePart = date.getElementById("time").innerHTML;

var teems = channels.getElementsByClassName("teems")[0];
var teemsDate = teems.getElementById("date").innerHTML;

var tv = channels.getElementsByClassName("tv")[0];
var tvChannel = tv.innerText;

Also note that your ids should be unique across the entire document.

DEMO.

like image 44
João Silva Avatar answered Sep 28 '22 16:09

João Silva


These are tasks which are made much easier with a DOM-centric Javascript library like jQuery, for which the code would be:

$('#channels .date').text();

An important thing to realise with native methods is that whereas getElementById will always return a single element, methods like getElementsByClass return collections of elements, which is one of the reasons your code isn't working (the other reason being that value is not a standard DOM element property: it's used for retrieving the current value of form elements).

The following document method, querySelectorAll works in all modern browser and IE from version 8 upwards (getElementsByClassName doesn't work in IE until version 9):

document.querySelectorAll('#channels .date'); 

To get the combined innerHTML of any elements this turns up (in your code it's just one, but it could be more), you will need to store that collection of elements in a variable and then loop through them to extract their innerHTML one by one:

var dates     = document.querySelectorAll('#channels .date');
var datesText = (function(){
    var string = '';

    for(var i = 0; i < dates.length; i++){
        string += dates[i].innerText;
    }

    return string;
}());
like image 52
Barney Avatar answered Sep 28 '22 14:09

Barney