Pawol Korzki
Pawol Korzki

Reputation: 3

Selecting element without element inside jQuery

I have this code:

<div class="external">
    <div class="view">
        <small class="times">×</small> 2        
    </div>
</div>

I want to select only the number, which I will compare and if bigger than one, I want to add CSS to it. I coded something like shown under, but the code doesn't work. The next problem is, that I can't use class view to target it, only the external. if I try .external:not(small) in CSS it works.

$().ready(function () {
    $('.external:not(small)').filter(function(index){
        return parseInt(this.innerHTML) > 1;
    }).css({'color':'red'});
});

Any ideas?

Upvotes: 0

Views: 152

Answers (2)

Mihai T
Mihai T

Reputation: 17687

You can filter the contents() of an element by nodeType. 3 returns the text nodes. Which is what you are looking for.

Then, wrap that element inside a span with a class and give that class any css styles you want.

$( ".view" ).contents().filter(function() {
      return this.nodeType === 3 && $.trim(this.nodeValue) !== ''
}).wrap( "<span class='number'></span>" )
span.number {
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="external">
  <div class="view">
  <small class="times">×</small> 2        
  </div>
</div>

Upvotes: 1

Syam Sagar
Syam Sagar

Reputation: 44

please wrap the number in span tag

<div class="external">
<div class="view">
<small class="times">×</small>
<span>2</span>        
</div>
</div>

$().ready(function () {
    let numTag = $('.external span');  //get span tag
    if (parseInt(numTag.text()) > 1) {  // check for the condition
         numTag.css({'color':'red'});  //apply your css
     }
});

Upvotes: 0

Related Questions