简体   繁体   中英

How to identify html elements that don't have a special id with jquery or otherwise?

I have a div filled with spans that don't have an id on them, and need to be able to determine if one of those spans is marked(highlighted). My approach at first was the following:

function isSelected(element){
  var selectedElement = window.getSelection().anchorNode.parentNode;
  if($(selectedElement).index() === $(element).index()){
    // It's selected
  }
}

But this solution doesn't consider cases where other elements from another div are selected that have the same index.

I tried comparing the element objects like this:

$(selectedElement).get() == $(element).get()

and like this:

$(selectedElement) == $(element)

but the comparison was always returning false.

How do I determine if they're the same without giving every span an id?

Solution:

if(selectedElement.isEqualNode(element){
}
if(selectedElement.isEqualNode(element){
}

This thread is discussing a topic related to your situation Object comparison in JavaScript

Maybe one of their suggestions helps you. Unfortunately Javascript does not provide anything like .ReferenceEquals() like for example C# does.

Try to use this code:

 if ($('div span .highlighted')){ alert ('span is highlighted'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div> <span class="highlighted"></span> <span class="normal"></span> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM