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

argument sent to component yields a result of undefined value

I am struggling with an asynchronous method that needs to be called in order to render a value on the first cycle. However, it seems that the component is being rendered before the value is returned, resulting in the prop being undefined when passed to the ...

Font Awesome symbols using the class "fa-brands" are not functioning as expected

I have included a font awesome library in the header using the following code: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> However, when I try to display an ic ...

Employing JavaScript for fading divs in and out sequentially

Hey there! I'm currently struggling with implementing transitions for my tool tips. Any assistance would be greatly appreciated! I am looking to have my "fader" divs fade in and out on click of a button, with each transition lasting 5 seconds. It&apo ...

Utilizing jquery and ajax to submit a form seamlessly without the need to refresh the web page

I've been struggling to submit a form without refreshing the entire page. I integrated some source code that I found, but for some reason, it's not working! Here is the HTML form I'm trying to submit: <form method="POST" action="" name= ...

What is the best way to determine if a child component's property has changed within a method?

The child component is app-google-maps-panel and has 2 properties in the parent component: <div class="col-6"> <app-google-maps-panel [longitude]="longitude" [latitude]="latitude"></app-google-maps-panel> & ...

Change the name of "rows" in the findAndCountAll method of Sequelize

Is there a way to change the key name for result.row when utilizing findAndCountAll in Sequelize? For pagination purposes, I am implementing findAndCountAll. The data structure I receive is as follows: { "count": 8, "rows": [ { ...

I cannot understand why I keep receiving <input type="email" value="required"> when all I want is <input type="email" value="" required>

Currently, I am working with PHP code and here is my complete PHP code: echo "<input type=\"email\" class=\"profil_input_text form-control\" name=\"user_email\" pattern=\"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(& ...

Transfer Data from a Factory to a Controller in AngularJS

Although it may seem like a simple question, it has taken me nearly 3 hours to try and figure out what went wrong here. Perhaps someone could help identify the issue and provide a solution (it seems like an easy fix, but I'm just not seeing it). So, h ...

Stop the Router from Displaying the Page momentarily prior to Redirecting

Currently, I have set up a session context for my NextJS application where users accessing pages within the /app/ directory are required to undergo an authorization check before being granted access. Although the logic is functioning correctly in redirect ...

Choose to either check or uncheck boxes using ReactJS

After successfully creating a function to select either single or multiple boxes, I encountered an issue with the "Select all" feature. Any suggestions on how to resolve this? (I'm utilizing the material-ui library for my checkboxes, which are essenti ...

What is the best way to compare two date strings with the format dd/mm/yyyy using JavaScript?

When attempting to compare a "Date" type of data with an "Any" type of data, the comparison is not functioning as expected. The date is retrieved in the following code: var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); v ...

Ways to avoid browser refresh when uploading files in React applications

I'm working with a simple file upload form in React using hooks. import React, { useState } from 'react'; import { FlexContainer } from '@styles/FlexContainer'; const TestUpload = () => { const [file, setFile] = useState<F ...

How can you implement CSS styling for Next.js HTML during server-side rendering?

Explore Next.js and observe the page request in the network tab. The preview displays not only the HTML but a fully pre-styled page as well. https://i.stack.imgur.com/deJLY.png When working with Styled-Components and Material-UI, they offer the ServerSty ...

search a database field by querying HTML form input

Looking for assistance with creating a query to input a code in an HTML form, search it against a database field, and display the corresponding database fields on a new page. I have already set up the database and established a working PHP script to connec ...

Encountering a Next.js event type issue within an arrow function

After creating my handleChange() function to handle events from my input, I encountered an error that I'm unsure how to resolve. Shown below is a screenshot of the issue: I am currently working with Next.js. In React, this type of error has not been ...

Ways to stop Google Places API from generating outcomes from a particular country

After carefully reviewing the entire documentation at https://developers.google.com/maps/documentation/javascript/reference/places-service#LocationRestriction, I am still unable to find a solution to my problem. I have successfully limited Google autocomp ...

Using JQuery to trigger CSS3 animations on one element when clicking on another

My Rails app has a feature similar to reddit where users can upvote or downvote content. I'm currently working on creating a CSS3 animation that triggers when a user clicks the downvote button. Here's how I'm using JQuery: <div class="a ...

Steps to Create a Repeating Melody/Instructions for Implementing a Loop Function

Currently, I am working with discord.js and have had success implementing various commands. However, I am having trouble creating a loop command for my discord bot. This specific command should play a song repeatedly until the loop command is executed ag ...

get the value of the last selected element using jQuery

I am facing an issue where I cannot retrieve the selected value from my second select element. Even though I have selected the second option in the dropdown, it keeps returning the value of the first option as empty. Here is a snippet of the HTML code: & ...

Overflow of Div Content

I need a way to showcase a collection of around 30 links in a horizontal layout without the links wrapping to a new line if they exceed the width of the parent container. A horizontal scroll should appear for users to navigate through the overflowing links ...