Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

asked on

Detect if Non-traditional element exists or not using Javascript

How would I check if this element exists on a page using Javascript? The "msgid" is unique.
User generated image
Thanks!
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

How about using getElementsByTagName?https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp

document.getElementsByTagName("oe-i18n-msg");

Open in new window


PS: Please use [ code ] tag without spaces to post code/content.
Avatar of MJ

ASKER

Unfortunately that Tag name ("oe-i18n-msg") is common.
What about using the max attributes we can like :

if( document.querySelectorAll('oe-i18n-msg.style-scope.session-timeout[msgid]').length ){
	console.log( 'Exist' );
}else{
	console.log( 'Not Exist' );
}

Open in new window

As has been stated by both Chimay and Zakaria, you can use either pure JavaScript or a library such as jQuery to do this.

jQuery:
var exists = $("oe-i18n-msg[msgid='1_SessionTimeout']").length > 0;

Open in new window


Pure JavaScript:
var exists = false;
var elements = document.getElementsByTagName("oe-i18n-msg");
for(var i = 0; i < elements.length; i++) {
  exists = elements[i].getAttribute('msgid') === '1_SessionTimeout';
  if(exists){
    break;
  }
}

Open in new window

Here's a working fiddle for both approaches.
If the tag is common how do you want to search for it?

There needs to be something we can search for.

You can find it by id like this
By Attribute value
if (document.querySelectorAll("[msgid='1_SessionTimeout']").length) {
  console.log('Exists');
}

Open in new window

If you want to find it by class then
if (document.getElementsByClassName('session-timeout').length) {
  console.log('Exists');
};

Open in new window


There are many ways to do this but to answer your question we need to know
What you know about the element that is going to be on the page - what unique consistent value will always be there.

Once we know that we can show you the code on how to find that.
Avatar of MJ

ASKER

Only the msgid will contain a unique ID of "1_SessionTimeout".
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MJ

ASKER

Thank you all!
You are welcome.