如何在仅含class无ID的div中获取指定<p>元素
Elements in Class-Only Divs
Since your div elements only have class attributes (no IDs), you can use CSS selector-based methods in vanilla JavaScript (or jQuery) to grab the nested <p> elements you need. Here are a few straightforward approaches:
Vanilla JavaScript Solutions
1. Get All Menu Items and Access Their
Elements
Use document.querySelectorAll() to fetch all .storeMenuTwoItem divs, then loop through them to extract the product name and price:
// Fetch all menu item containers const menuItems = document.querySelectorAll('.storeMenuTwoItem'); // Iterate over each item to get its details menuItems.forEach(item => { const productName = item.querySelector('.storeMenuTwoBodyText').textContent; const productPrice = item.querySelector('.storeMenuTwoBodyPrice').textContent; // Example: Log the details console.log(`Product: ${productName}, Price: ${productPrice}`); });
2. Target a Single Specific
Element
If you only need one specific element (like the price of the first item), combine class selectors directly:
// Get the price of the first menu item const firstItemPrice = document.querySelector('.storeMenuTwoItem .storeMenuTwoBodyPrice').textContent; console.log(firstItemPrice); // Outputs "23 R$"
3. Access Elements When the Div is Clicked
Since your divs have an onclick="addToCart()" handler, you can use this inside the function to reference the clicked div and get its nested elements:
function addToCart() { // "this" refers to the div that was clicked const selectedProduct = this.querySelector('.storeMenuTwoBodyText').textContent; const selectedPrice = this.querySelector('.storeMenuTwoBodyPrice').textContent; // Use these values to handle adding to cart alert(`Adding ${selectedProduct} for ${selectedPrice} to your cart!`); }
jQuery Solution (If You're Using It)
If your project uses jQuery, the syntax is even more concise:
// Get all product names and log them $('.storeMenuTwoItem .storeMenuTwoBodyText').each(function() { console.log('Product:', $(this).text()); }); // Get the price of the second menu item (index starts at 0) const secondItemPrice = $('.storeMenuTwoItem').eq(1).find('.storeMenuTwoBodyPrice').text(); console.log(secondItemPrice);
All these methods work because they leverage CSS combinators to target nested elements by their class names—no IDs required!
内容的提问来源于stack exchange,提问作者Matheus Soares Kirchesch

