简体   繁体   English

如何使用javascript获取div内的div值?

[英]How do I get the value of a div inside a div using javascript?

I need to figure out how to either set the ID of the last Div, or get the value of the last DIV. 我需要弄清楚如何设置上一个Div的ID或获取上一个DIV的值。 I can't use the classes below, as they're used over & over in the code. 我不能使用下面的类,因为它们在代码中反复使用。 Perhaps nodechilds of the main one? 也许是主要节点的子节点?

I've tried searching around, with no luck. 我尝试四处搜寻,但没有运气。

<div class="designer-object adapter" id="73c8f274-e14f-4891-126e-67019bb100d1" data-previewcolor="" zindex="10008" style="width: 140px; height: 22px; left: 916px; top: 90px; z-index: 10008; opacity: 1;">
  <div class="labelControl">
    <div class="labelControlLabel" style="overflow: visible;">
      <div class="labelControlLabelTable">
        <div class="labelControlLabelCell" style="text-align: center; vertical-align: middle;">System Administrator</div>
      </div>
    </div>
  </div>
</div>

Need to return value System Administrator 需要返回值System Administrator

Firstly, you can scope your query selector by either invoking querySelector on a particular node rather than document , or by using the child ( ab ) or descendant ( a>b ) selectors. 首先,您可以通过在特定node而不是document上调用querySelector查询选择器的范围,或者使用子( ab )或后代( a>b )选择器。

Secondly, to get the text of a div, simply read the textContent property. 其次,要获取div的文本,只需读取textContent属性。

let parentId = '73c8f274-e14f-4891-126e-67019bb100d1';
let text = document.querySelector(`#${parentId} .labelControlLabelCell`).textContent;
console.log(text); // System Administrator 

Just use getElementsByClassName() and use an index. 只需使用getElementsByClassName()并使用索引即可。 Here is a good Good explanation for what it is. 这是一个很好的解释 When using it, document.getElementsByClassName("labelControlLabelCell")[index] where index is number of the div, starting from 0. So you have to do some counting but it works. 使用它时, document.getElementsByClassName("labelControlLabelCell")[index]其中index是div的数字,从0开始。因此您必须进行一些计数,但是它可以工作。

Just assign an id to the element as below: 只需为元素分配一个id,如下所示:

<div class="labelControlLabelCell" id="dummyId" style="text-align: center; vertical-align: middle;">System Administrator</div>

then use following method to get the content: 然后使用以下方法获取内容:

var x = document.getElementById("dummyId").textContent;

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

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