在javascript中按div下的名称查找元素
我想获取特定名称下的标签节点列表,但我无法这样做。 我有一个功能,在按钮上的“点击”事件触发在javascript中按div下的名称查找元素,javascript,Javascript,我想获取特定名称下的标签节点列表,但我无法这样做。 我有一个功能,在按钮上的“点击”事件触发 let button = event.target; let shopItem = button.parentElement.parentElement; let price = shopItem.getElementsByClassName("shop-item-price")[0].innerText; let sizePrices = document.getElements
let button = event.target;
let shopItem = button.parentElement.parentElement;
let price = shopItem.getElementsByClassName("shop-item-price")[0].innerText;
let sizePrices = document.getElementsByName("sizes");
现在,元素的层次结构如下所示<代码>控制台.log(shopItem)等同于以下内容:-
<div class="shop-item" id="2">
<span class="shop-item-title">Veggie Supreme</span>
<img class="shop-item-img" src="Images/pizza.png" width="200" height="200">
<div class="shop-item-details">
<div class="shop-item-sizes">
<input type="radio" value="100" name="sizes">
<label>Small</label>
<input type="radio" value="200" name="sizes">
<label>Medium</label>
<input type="radio" value="300" name="sizes">
<label>Large</label>
</div>
<span class="shop-item-price">Rs.Rs.250</span>
<button class="btn btn-primary shop-item-button">ADD TO CART</button>
</div>
</div>
素食至上
小的
中等
大的
250卢比
添加到购物车
我想利用shopItem按名称“大小”查找元素,但我无法使用shopItem.getElementsByName
,这就是为什么我使用document.getElementsByName
,但这会提供整个页面中的所有标记。我只想要shopItem下的“尺码”。
如何解决此问题?您可以这样做:
const nodes=document.querySelectorAll('.shop item[name=“size”]');
console.log(节点)代码>
素食至上
小的
中等
大的
250卢比
添加到购物车
让sizePrices=shopItem.GetElementsByCassName(“大小”);
小的
中等
大的
我给标签分配了一个类。这似乎不是一种有效的方法,但它暂时有效。你可以试试这个
const nodes = document.querySelectorAll('div.shop-item-sizes > input[name="sizes"]');
console.log(nodes);
如果要将其转换为数组
const nodesArray = Array.from(nodes);
console.log(nodesArray);
谢谢你的回答。我试过了。我的网页上有多个项目。。其中每个项目有3个标签。我尝试了上面的代码,“节点”总是对应于第一个项目标记。好的,我已经更新了,试试看,它现在显示了所有的标记。我一共有12个标签。。当我执行console.log(节点)时,它显示了所有这些
const nodesArray = Array.from(nodes);
console.log(nodesArray);