Ibos
Ibos

Reputation: 82

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){
}

Upvotes: 0

Views: 99

Answers (3)

Ibos
Ibos

Reputation: 82

if(selectedElement.isEqualNode(element){
}

Upvotes: 1

Larsupilami
Larsupilami

Reputation: 58

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.

Upvotes: 0

Felix Haeberle
Felix Haeberle

Reputation: 1606

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>

Upvotes: 0

Related Questions