简体   繁体   中英

Javascript scraper find element attribute by class name

i've this simple javascript scraper, used to a local page.

I would find the id attribute of all the "title" class element.

The trouble is that, when i go to print the variable on the screen, the variable (title1) is ever "undefined" and not "xxx" like it must be.

What is wrong?

The local page:

<!DOCTYPE HTML>
<html>
<body>
<div class="title" id="xxx"> xyz</div>
</body>

The (partial) code:

{ 
    $.get("http://localhost/new.php", function(html) {  
        var title1 = $(html).find(".title").attr("id");
        document.getElementById("1").innerHTML = title1;
    })
}

This is because .title is a direct element .. you can use $(html).filter('.title').attr('id') or wrap the .title div inside another div

 var html = '<div class="title" id="xxx"> xyz</div>'; alert($(html).filter('.title').attr('id')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Wrap div

 var html = '<div><div class="title" id="xxx"> xyz</div><div>'; alert($(html).find('.title').attr('id')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

working example

 var html = '<div class="title" id="xxx"> xyz</div>'; var FindId = $(html).filter('.title').attr('id'); $('#1').html(FindId); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="1"></div> 

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