简体   繁体   English

在DOM元素内选择

[英]Selecting inside a DOM element

This is the html code 这是HTML代码

<div class="extra-sub-block sub-block-experience">
    <h6 style="display:inline;" id="exp-pos-0" class="extra-sub-block-head sub-block-head-experience">CEO</h6>
</div>
<div class="extra-sub-block sub-block-experience">
    <h6 style="display:inline;" id="exp-pos-1" class="extra-sub-block-head sub-block-head-experience">COO</h6>
</div>

There are several such similar structures. 有几种类似的结构。 Now I try to extract the values from each block. 现在,我尝试从每个块中提取值。

var temp=document.getElementsByClassName('sub-block-experience');
var result=$(temp[0]+"#exp-pos-0");

This throws an error. 这将引发错误。 I followed selecting element inside another DOM 我跟随选择另一个DOM中的元素

I also tried 我也试过

var temp=document.getElementsByClassName('sub-block-experience');
var result=temp[0].find('h6');

This doesn't work as well. 这也不行。 What am I doing wrong here. 我在这里做错了。 Help? 救命?

For extracting the values from all blocks, you can use .map() function as follows: 要从所有块中提取值,可以使用.map()函数,如下所示:

var results = $('.extra-sub-block-head').map(function(){
  return $(this).text();
})

Demo 演示

side note: Since id is unique in a document, you can directly access the element using id selector like var result= $("#exp-pos-0"); 旁注:由于id在文档中是唯一的,因此您可以使用id选择器直接访问元素,例如var result= $("#exp-pos-0"); instead of var result=$(temp[0]+"#exp-pos-0"); 而不是var result=$(temp[0]+"#exp-pos-0");

Try, var result=$(temp[0]).find('h6'); 试试, var result=$(temp[0]).find('h6');

Even, in the documentation link that you gave in question, it shows that you should wrap your result from document.getElementById in $() to be applied with jQuery. 甚至在有问题的文档链接中,它表明您也应该将来自document.getElementById的结果包装在$() ,以与jQuery一起使用。 What it does is, that it converts the native javascript object into a jquery object. 它的作用是将本地javascript对象转换为jquery对象。

Demo 演示

 function testIt(){
    var tags, index;
    tags = document.getElementsByTagName('h6');
  for (index = 0; index < inputs.length; ++index) {
    //do something ...
  }
 }

If I am correct you are trying to get ceo and coo?.If that's the case then with jquery: 如果我是对的,那么您正在尝试获得首席执行官和首席运营官?

var x= $('.extra-sub-block h6');
//values are
$(x[O]).html();
$(x[1]).html();

You could also use plain javascript: 您还可以使用普通的javascript:

var result = document.querySelectorAll('.sub-block-experience h6');

Or if you like it separate: 或者,如果您希望单独使用它:

var temp = document.querySelectorAll('.sub-block-experience');
var result = [];
for(var i = 0, elem; elem = temp[i]; i++) {
  result = result.concat(elem.querySelectorAll('h6'));
}

But be aware of the browser compatability of querySelectorAll and querySelector . 但请注意querySelectorAllquerySelector的浏览器兼容性。

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

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