[英]How can I extract the nested value from this Javascript/HTML code?
In this code, I want to extract the value "Yes, I am a Speaker" through Javascript DOM element. 在此代码中,我想通过Javascript DOM元素提取值“是的,我是发言人”。 By using getElementById. 通过使用getElementById。 But, I do not know how to access the value as it is nested inside the list element and the list doesn't have any value and attribute. 但是,我不知道如何访问该值,因为它嵌套在list元素内,并且列表没有任何值和属性。 And, in this code only list has a unique id to select this element. 并且,在此代码中,只有列表具有唯一的ID才能选择此元素。 There are several such blocks of code with unique list id. 有几个具有唯一列表ID的代码块。 I would appreciate if there is a quick help. 如果有快速的帮助,我将不胜感激。 I am using this for creating GTM custom javascript variable. 我正在使用它来创建GTM自定义javascript变量。
<li id="u5mH6ZV1aX21" class="container step2" style="width: 232px;">
<input type="hidden" name="value" value="Yes, I am a smoker" autocomplete="off">
<div class="letter"><span>A</span></div>
<span class="label">Yes, I am a smoker</span>
<span class="tick"></span>
<div class="aux">
<div class="bg"></div>
<div class="bd"></div>
</div>
</li>
So select the element by the class or element type 因此,请根据类别或元素类型选择元素
var t1 = document.querySelector("#u5mH6ZV1aX21 input").value var t2 = document.querySelector("#u5mH6ZV1aX21 .label").textContent console.log(t1, t2);
<ul> <li id="u5mH6ZV1aX21" class="container step2" style="width: 232px;"> <input type="hidden" name="value" value="Yes, I am a smoker" autocomplete="off"> <div class="letter"><span>A</span></div> <span class="label">Yes, I am a smoker</span> <span class="tick"></span> <div class="aux "> <div class="bg"></div> <div class="bd"></div> </div> </li> </ul>
You can use the modern querySelector
API to select a specific element using the fact that you know the unique ID and the type (or "tagName") of the child element you're trying to access. 您可以使用现代的querySelector
API来选择特定的元素,因为您知道您要访问的子元素的唯一ID和类型(或“ tagName”)。
MDN article on querySelector 有关querySelector的MDN文章
document.querySelector("#u5mH6ZV1aX21 input").value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.