Determine if a div contains an svg element with JavaScript

My question involves a div containing a question mark and some SVG elements. Here is the initial setup:

<div id="mydiv">?</div>

When validating a form submission in my code, I check if the div text contains a question mark like this:

const fieldText = $('#mydiv').text();
return fieldText.indexOf('?') !== -1;

Now, the content of the div includes an SVG question mark instead of just a plain text one:

<div id="mydiv">
  <svg version='1.1' id='Layer_1' class='q-mark-svg' xmlns='http://www.w3.org/2000/svg' ... >
    <!-- SVG path data here -->
  </svg>
</div>

I need to modify my JavaScript validation to now check for the presence of an SVG element within the div rather than just a question mark. How can I achieve this?

I attempted the following approach by searching for 'svg' in the div text, but it did not work as expected:

const fieldText = $('#mydiv').text();
return fieldText.indexOf('svg') !== -1;

Answer №1

Instead of using jQuery, consider utilizing vanilla javascript and the getElementsByTagName method to retrieve a list of matching elements within specific containers. You can then check the length of the returned array (where 0 indicates false in the condition).

Here is an example: Conducting two tests, one involving an svg element inside a div, and one without:

var t1 = document.getElementById('test1');
var t2 = document.getElementById('test2');

// Implementing a basic conditional check
if (t1.getElementsByTagName('svg').length) {
  console.log('test1 contains svg');
}
if (t2.getElementsByTagName('svg').length) {
  console.log('test2 contains svg');
}
<div id='test1'></div>
<div id='test2'><svg></svg></div>

Answer №2

Give this a try $('#mydiv').find('svg').length)

When the svg is present, you will receive a value for the length. If not, the value will be 0.

I hope this information proves useful to you.

Answer №3

Locate the svg element within a div.

if($("#mydiv").find("svg").length) {
   alert("SVG element found");
} else {
    alert("No SVG element found");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="mydiv">
   <svg version='1.1' id='Layer_1' class='q-mark-svg' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'
  viewBox='0 0 50 50' style='enable-background:new 0 0 50 50;' xml:space='preserve'>
  <style type='text/css'>
     .q-mark{fill:#777777;}
  </style>
  <g>
     <g>
        <path class='q-mark' d='M18.3,17.2c0,0.4-0.1,0.7-0.2,1c-0.1,0.3-0.3,0.6-0.5,0.8c-0.2,0.2-0.5,0.4-0.8,0.5c-0.3,0.1-0.6,0.2-1,0.2
           c-0.7,0-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8c0-1.6,0.3-3.2,0.9-4.6c0.6-1.4,1.5-2.7,2.6-3.8s2.3-1.9,3.8-2.5
           c1.4-0.6,3-0.9,4.6-0.9s3.1,0.3,4.6,1c1.4,0.6,2.7,1.5,3.8,2.6s1.9,2.3,2.6,3.8c0.6,1.4,0.9,2.9,0.9,4.5c0,3.2-1.2,6-3.5,8.4
           l-3.8,3.5c-1.3,1.3-2,2.7-2,4.3c0,0.7-0.2,1.3-0.7,1.8c-0.5,0.5-1.1,0.7-1.8,0.7s-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8
           c0-2.9,1.2-5.6,3.5-7.9l3.8-3.6c-...
        

Answer №4

Give this a shot:

if($("svg")[0]){
    console.log("it's there!");
} else { 
    console.log("nowhere to be found");
}

Answer №5

Try using either of the following codes to check for the existence of an SVG element within a div with ID "mydiv":

document.querySelector("#mydiv svg") !== null

or
document.querySelector("#mydiv svg").querySelector("svg") !== null

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connect a controller in AngularJS to a service property

I've been encountering an issue with updating my value in the controller. Initially, it works fine with the property value but fails to update later on. Despite trying various methods and going through multiple threads, I can't seem to get it to ...

Is it possible to protect assets aside from JavaScript in Nodewebkit?

After coming across a post about securing the source code in a node-webkit desktop application on Stack Overflow, I began contemplating ways to safeguard my font files. Would using a snapshot approach, similar to the one mentioned in the post, be a viable ...

There are no specified operations outlined in the Node.js Express documentation

swagger ui https://i.stack.imgur.com/UIavC.png I've been struggling to resolve this issue where the /swagger endpoint seems to only partially read the swagger.json file. Despite configuring everything correctly, no errors are appearing. It simply dis ...

Header Menu Click Causes Blurring of Website Background

I need help adding a blur effect to my site background only when the header menu is clicked and active. Once the menu is activated, the .ct-active class is added to it. The CSS code below works for styling individual items - the menu turns red when activ ...

How to Filter, Sort, and Display Distinct Records in an HTML Table with jQuery, JavaScript, and

In the HTML page, there will be a total of 6 tabs labeled A, B, C, D, E, and F along with 2 dropdowns. The expected behavior is as follows: The user will choose a value from the 2 dropdown menus. Based on the selected value, filtering should be applied to ...

Serialize a web form to transmit it through Ajax requests

I am looking to utilize Ajax to send a form instead of using a submit button. In the code below, I have defined the form and added a jQuery function to handle the action when the CREATE BUTTON is clicked. During debugging, I found that console.log($(&ap ...

Directly within Angular, map the JSON data to an object for easy assignment

I came across this information on https://angular.io/guide/http. According to the source, in order to access properties defined in an interface, it is necessary to convert the plain object obtained from JSON into the required response type. To access pr ...

Tips for compressing JavaScript on the fly

Is there a method to dynamically compress JavaScript, similar to how gzip functions for HTML (and apparently CSS)? I'm looking for a solution where I don't have to manually compress the file before uploading every time. I want the server to hand ...

Guide to integrating custom fields in Wordpress with mapbox-gl js to generate map markers

Currently, I am in the process of generating a map that will display various points using Mapbox and WordPress. To achieve this, I have set up a custom post type within WordPress where the coordinates are stored in custom meta fields. Although the fields h ...

What is the best way to extract the chosen value from a dropdown menu within the $_POST array?

In my HTML code, I have a droplist using the <select> tag. How can I retrieve the selected value from the $_POST array once the user submits the form? <form action="subj_exec.php"> <?php echo $_SESSION['SESS_MEMBER ...

Combine the arrays to utilize ng-repeat

I'm working with several arrays and I need to display them in a table using ng-repeat. Is there a way to combine arrays like name=[name1, name2] and type=[type1, type2] into a single array data=[..] so that I can use ng-repeat for data.name and data.t ...

Issues with dynamically adding or removing scroll in jQuery are not being resolved

I am trying to implement a dynamic scrolling feature in my post scenario. The goal is to automatically add a vertical scroll when the number of dynamic inputs reaches a certain threshold. Specifically, if there are more than 5 dynamic inputs created, a ver ...

What is the best way to navigate back to the top of the page once a link has been clicked?

One issue I'm facing is that whenever I click on a link in NextJS, it directs me to the middle of the page: <Link href={`/products/${id}`} key={id}> <a> {/* other components */} </a> </Link> I believe the problem l ...

What is the best way to pass a value to a PHP file and then redirect to it?

I am facing an issue with retrieving the id of a button with "orderdetail" class in an HTML document using jQuery. I want to pass this id to a PHP document, redirect to that PHP file, and then process the id using POST method. However, I keep getting an er ...

Tips for implementing the f11 effect with a delay of 5 seconds after pressing a key in JavaScript or jQuery

Is there a way to activate the F11 effect only 5 seconds after pressing a key using JavaScript or jQuery? ...

The Kendu UI Tabsbstrip views are experiencing issues with loading jquery validation

While using Kendo UI's Tabstrip, I encountered an issue. Specifically, I have two tabs within the tabstrip and I would like to implement client-side jQuery validation in one of the views under the tabstrip. Here is what it looks like on Google Chrome ...

What are the steps to create parallel curves in three.js for road markings?

My goal is to create parallel curved lines that run alongside each other. However, when I try to adjust their positions in one axis, the outcome is not what I expected. The code I am using is fairly simple - it involves a bezier curve as the central path ...

Identifying and handling the removal of a complete div element by the user

Is it possible to remove the entire div element if a user tries to inspect the web browser using the script provided below? <script type="text/javascript"> eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/, ...

Are you looking to work with an ASMX web service and navigate JSON utilizing JavaScript or

Currently, I am using asmx to fetch data from a database. public class TestPage1 { public int UserID { get; set; } public string UserName { get; set; } public string Password { get; set; } public string FirstName { get; set; } public ...

Issue encountered while utilizing property dependent on ViewChildren

Recently, I designed a custom component which houses a form under <address></address>. Meanwhile, there is a parent component that contains an array of these components: @ViewChildren(AddressComponent) addressComponents: QueryList<AddressCo ...