admin管理员组

文章数量:1355570

I have a table with 33 inputs with ID's ranging from 1 - 33. So for example they range from "price-1" all the way to "price-33"

Instead of individually define these elements one by one like this:

var p1 = document.getElementById("price-1");
var p2 = document.getElementById("price-2");

How can I automatically count (perhaps count by the price- prefix?) and define each of these elements using JavaScript (or jQuery if it's easier)?

I have a table with 33 inputs with ID's ranging from 1 - 33. So for example they range from "price-1" all the way to "price-33"

Instead of individually define these elements one by one like this:

var p1 = document.getElementById("price-1");
var p2 = document.getElementById("price-2");

How can I automatically count (perhaps count by the price- prefix?) and define each of these elements using JavaScript (or jQuery if it's easier)?

Share Improve this question asked Feb 22, 2020 at 10:15 tonytony 6346 silver badges27 bronze badges 4
  • You may be better off using a data field and loading them into an array. – Trace Commented Feb 22, 2020 at 10:17
  • Could you provide an answer with it in an array? I'd be interested to see. – tony Commented Feb 22, 2020 at 10:23
  • @Trace - I'd really love an example of your solution. – tony Commented Feb 22, 2020 at 10:34
  • Give me a minute to formulate an answer with motivation – Trace Commented Feb 22, 2020 at 10:39
Add a ment  | 

4 Answers 4

Reset to default 8

You can try using Attribute selectors ( starts with:- [attr^=value]):

Represents elements with an attribute name of attr whose value is prefixed (preceded) by value.

Demo: Using vanilla JS:

var elList = document.querySelectorAll('[id^=price-]');
console.log(elList.length); //5

//loop throgh all the elements whose id starts with price-
var data = {};
elList.forEach(function(el){
  data[el.id] = el.value;
});
console.log(data);
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="price-1" value="100"/>
<input id="price-2" value="200"/>
<input id="price-3" value="300"/>
<input id="price-4" value="400"/>
<input id="price-5" value="500"/>

OR: Using jQuery

var count = $('[id^=price-]').length;
console.log(count); //5

//loop throgh all the elements whose id starts with price-
var data = {};
$('[id^=price-]').each(function(){
  data[this.id] = this.value;
});
console.log(data);
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="price-1" value="100"/>
<input id="price-2" value="200"/>
<input id="price-3" value="300"/>
<input id="price-4" value="400"/>
<input id="price-5" value="500"/>

You can use querySelectorAll for this purpose:

// Get all elements where id starts with `price` text
const prices = document.querySelectorAll('*[id^="price"]');

// Loop through each one of them
[...prices].forEach(price => {
  console.log('id: ', price.id);
  console.log('value: ', price.value);
});
<input type="text" id="price-1" value="10" />
<input type="text" id="price-2" value="20"/>

try this:

document.querySelectorAll('[id^="price-"]').forEach((el, i) => console.log(el, i))

The motivation why I would prefer to use a data field is because I consider id to be a unique identifier related to the DOM element.

Your example doesn't suggest price being a unique identifier, but rather a workaround to allow crawling the DOM for price element.
Even when it would concern a unique identifier, let's say an id as primary key from a database, I would use something like data-id, as this more descriptively mentions that we are talking about the actual data rather than a DOM element's id that may or may not be just a generic description that merely focuses on uniqueness.

Because of this, it makes more sense to have a generic attribute to identify the price (this anything you want it to be semantically), and you can allocate custom data field that you want to retrieve later in your javascript code.

Without being fancy:

<div>
    <div data-type="price" data-price='5'>5<span>$</span></div>
    <div data-type="price" data-price='6'>6<span>$</span></div>
</div>

var prices = document.querySelectorAll("[data-type='price']");

for (let i = 0; i < prices.length; i++) {
    console.log('price:', prices[i].getAttribute('data-price'));
}

https://jsfiddle/b03c7ars/

本文标签: