Forum Moderators: open

Message Too Old, No Replies

test involving jQuery and append()

         

Bundy2

5:45 am on Dec 1, 2020 (gmt 0)

5+ Year Member



Hi all,
Thinking out loud...
I want to test if a certain element, one <p> amongst many, is on view and in a certain state. Let's call it <p id="test">.
Prior to this test, "p#test" may have undergone two changes.

It may have been set to "display:none", in which case we're testing for "display:none" being false:
if ( ($('p#test').css('opacity') !== 0) ) 

Then the hard part: "p#test" may also have been modified with jQuery .append():
 $('p#test').append('<span class="add"> yes</span>'); 

How to test whether, as a second condition, "yes" has been added to "p#test" ? maybe
 if ( ($(p#test).css('opacity') !== 0) && ($('p#test span').hasClass('add')) ){ do something } 
?

This looks ok, but will be difficult to confirm by testing as there is only one situation among hundreds.
Also, It would be logically better to test if there actually is a span, but I can't see how to do this.
Any comments will help.
cheers

NickMNS

12:59 am on Dec 2, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It would be logically better to test if there actually is a span

That is correct. The simplest way to do that, is to forget about jQuery and just use plain vanilla JS


const spanElem = document.querySelector('#test span')
if (spanElem) { //do something }

//if you are coding using ES5 (eg for older browsers use var instead of const)

Bundy2

7:37 am on Dec 2, 2020 (gmt 0)

5+ Year Member



NickMNS, Many thanks!

robzilla

8:41 am on Dec 2, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Opacity and display are different CSS attributes. If it's "display: none" you're after, why test for opacity?

Bundy2

10:24 am on Dec 2, 2020 (gmt 0)

5+ Year Member



Correct, it should be if ( ($('p#test').css('display') !== 0) ).
(There are other cases where a <p> has been modified using opacity, fadeTo(); my confusion...)

jpmmedia

3:20 pm on Dec 9, 2020 (gmt 0)

5+ Year Member Top Contributors Of The Month



just use
console.log($('p#test').css('display')); to see the value set for display

then for example,

if ($('p#test').css('display') !== 'block')

Says if the document element of p with a id of test does not have the style of display block do something