Wituz
Wituz

Reputation: 2023

Extract HTML with javascript

Here comes a simple question, for all those who know javascript. I made an application, which grabs the following code and puts it into a variable:

<div class="article-author">Af <span class="remove_from_bt_touch">:</span>Af Tho
mas S&oslash;gaard Rohde, Berlingske Nyhedsbureau<span class="section-time">&nbs
p;15. jan. 2012
               |
            </span>
<span class="section-category">Danmark</span>
</div>

Now, what I want is another variable, containing the DATE of the variable above. So it should be 15. jan. 2012.

How do I do that?

Upvotes: 0

Views: 104

Answers (2)

RobG
RobG

Reputation: 147343

Don't really understand what you mean by "puts it in a variable" other than to say the markup is a string assigned to a variable like:

var m = '<div class="article-author">Af ' +
        '<span class="remove_from_bt_touch">:<\/span>' +
        'Af Thomas S&oslash;gaard Rohde, Berlingske' +
        ' Nyhedsbureau<span class="section-time">&nbsp;' +
        '15. jan. 2012 | <\/span>' +
        '<span class="section-category">Danmark<\/span><\/div>';

If that is the case, you can get the date (provided it is exactly in the format shown) using match with a regular expression:

var re = /\d\d?\. [a-z]{3}\. [0-9]{4}/;

alert(m.match(re)); // 15. jan. 2012       

However, if you mean it is markup in a page and you are trying to get the text in the span with class section-time, then you can use something like:

// Get all elements with class section-time, use DOM method, 
// querySelectorAll or some other means
var el, els = document.getElementsByClassName('section-time');

// Get the date out of each. Use a regular expression as there
// seems to be other stuff in there
var dates = [];
var re = /\d\d?\. [a-z]{3}\. [0-9]{4}/;

for (var i=0, iLen=els.length; i<iLen; i++) {
  el = els[i];
  dates.push((el.innerText || el.textContent).match[0]);
}

Or you could get all such dates in an array using match with the above regular expression on the innerHTML of a common parent element.

Upvotes: 2

erikvimz
erikvimz

Reputation: 5476

var date = $('.section-time').text();

Using jQuery of course.

Upvotes: 1

Related Questions