简体   繁体   English

带有类和ID的javascript抓取跨度标签

[英]javascript grabbing span tag with both class and id

I have a span tag 我有一个跨度标签

<span class="vi-is1-prcp" id="v4-25">US $99.00</span>

I would like to grab it using pure javascript. 我想使用纯JavaScript来抓取它。 JQuery or any other library is not allowed. 不允许使用JQuery或任何其他库。 Is that possible? 那可能吗?

I recon that 我确认

getElementById('v4-25')

won't work since I have to specify class, too, correct? 因为我也必须指定班级,对吗?

Thank you, 谢谢,

So, 所以,

<div id="listprice">asdasdasdasdasd</div>
var string = document.getElementById('v4-25');
document.getElementById('listprice').innerHTML = string;

should print value of 'v4-25' in 'listpirce' ? 应该在'listpirce'中打印'v4-25'的值?

H H

getElementById will work just fine. getElementById将正常工作。 Just make sure you're running it after the page has loaded. 只要确保在页面加载后就在运行它即可。

There is no reason to add a class. 没有理由添加一个类。 Run the script after that dom element is loaded like this. 这样加载dom元素后运行脚本。

<span class="vi-is1-prcp" id="v4-25">US $99.00</span>
<script>
    var elm = document.getElementById('v4-25');
</script>

First of all, ids are unique. 首先,ID是唯一的。 You can't have more than one. 您最多只能有一个。 therefore, when you select element by id, you can only bring back one element (this is good). 因此,当您通过ID选择元素时,您只能带回一个元素(这很好)。

Secondly, after you get an element, you have to do something with it. 其次,获得元素后,必须对其进行处理。 var string = document.getElementById('v4-25'); only gets you the element, but it looks like you want var string = document.getElementById('v4-25').innerHTML; 仅获取您的元素,但看起来您想要var string = document.getElementById('v4-25').innerHTML; for the price. 价格。 If you do want the id instead you can do var string = document.getElementById('v4-25').id; 如果您确实想要ID,则可以执行var string = document.getElementById('v4-25').id; but because that just returns "v4-25" it's a bit redundant. 但是因为它只返回“ v4-25”,所以有点多余。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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