简体   繁体   中英

Extracting specific lines in a chunk of text which contains a specific word, javascript

I am currently have a chunk of string which actually a html source code stored in it. What I am trying to do now is to read out specific tags which I require using javascript. Can anyone help me with this, I am new to programming and I am not too sure how to go about it.


The problematic code:

if (request.readyState == 4) {
    var html_text = request.responseText;
    var parent = document.createElement('div');
    parent.innerHTML = html_code;
    var metas = parent.getElementsByTagName('meta');
    var meta;
    for (var i = 0; i < metas.length; i++) {
        meta = metas[i];
        alert(meta.property);
        alert(meta.content);
    }
}

The meta content works, but just that the meta property returned are undefined.

Use the DOM (Document Object Model) API. The Mozilla Dev Network ( née Mozilla Dev Center) is a great starting point an all-around reference.


What I am trying to do now is to read out specific tags which I require using javascript.

var text = /* whatever string that contains HTML */;

First you need to parse the string:

var parent = document.createElement('div');
parent.innerHTML = text;

Then you can search for whatever kind of element you're looking for. Say you're looking for <table> elements.

var tables = parent.getElementsByTagName('table');

Now you can do whatever you need to each element found:

var table;
for (var i=0, len=tables.length; i<len; i++)
{
    table = tables[i];
    // do something with the element
}

Relevant API docs

Attributes of XML nodes are not readily available as DOM object properties. Use getAttribute

Sample: http://jsfiddle.net/mendesjuan/6Pdmw/

var node = document.createElement('div');
node.innerHTML = "<meta property='prop1' content='cont1'>"+
                 "<meta property='prop2' content='cont2'>";
var metas = node.getElementsByTagName('meta');    
for (var i = 0; i < metas.length; i++) {
    var meta = metas[i];
    alert(meta.getAttribute("property"));
    alert(meta.getAttribute("content"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM