Check the existence of an element by the Value attribute?

Asked

Viewed 367 times

1

I need to basically check if a certain div exists within a list, the structure is like this:

<div class="content" id="divCheck">
   <div class="filho" value="1"></div>
   <div class="filho" value="2"></div>
   <div class="filho" value="3"></div>
</div>

<div class="content">
   <div class="filho" value="1"></div>
   <div class="filho" value="2"></div>
   <div class="filho" value="3"></div>
</div>

How can I check if in the div with id divCheck there is an element with some value, it would be correct to make a each in this div or to do this with a simple if even?

  • 1

    That code of yours is strange, <div>without closing them, and with values... That’s the code?

  • I forgot to close, but the code is just an example to simplify the understanding of the question. But yes the values are necessary, maybe I will change to the attribute "date-" in the future.

  • Oh yes, but what exactly do you want? check if there is a certain element? Or take all the elements within it that have some value?

  • Just check if within a certain div there is any element with that Value, such attribute in this case will be unique of that element within the div, and need to manipulate differently if it already exists, if I should not add a

  • Why don’t you use class/id in place of value, since they are not text(input) fields and this property will not be displayed to the user. This is usually done when you want to reference an element or even check if it exists.

1 answer

3


No loop needed. You can use a selector to find whether or not there is an element with an attribute and/or a value:

var existsValue1 = document.querySelector('#divCheck div[value="1"]');
console.log(!!existsValue1); //true

var existsValue8 = document.querySelector('#divCheck div[value="8"]');
console.log(!!existsValue8); //false
<div class="content" id="divCheck">
   <div class="filho" value="1"></div>
   <div class="filho" value="2"></div>
   <div class="filho" value="3"></div>
</div>

<div class="content">
   <div class="filho" value="1"></div>
   <div class="filho" value="2"></div>
   <div class="filho" value="3"></div>
</div>

  • Thanks bro that’s just what I needed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.